2017-05-18 24 views
1

我需要一個建議。情況如下:C#:根據值切換返回值類型

我有一個用於操作一些硬件的庫。 Quant的其中一個參數是Quant(應包裝多少個產品)。它可以是三種類型:

*quant type | value type* 
Weight  | double 
Pieces  | Integer 
Without | null 

我可以創建一個結構,用於存儲定量值,例如:

public struct Quant 
{ 
    public QuantTypes QuantType { get; set; } 
    public double QuantWeightValue { get; set; } 
    public int QuantPieceValue { get; set; } 
    ... 
} 

但在工作過程中,我需要檢查很多次的狀態和定量的價值。它變得困難,因爲我需要取決於quantType的價值

if(QuantType == QuantTypes.Piece) 
{ 
    if(QuantWeightValue > 5) 
      QuantWeightValue += 2.5; 
} 
else 
{  
    if(QuantPieceValue > 5) 
      QuantPieceValue += 2; 
} 
SetNewQuantToMachine(); 

我不喜歡它。我只能爲雙重類型的定量值創建一個字段。但是這樣的方式開啓了一種設置非整數值片段類型的量化的可能性。在這種情況下,我看到兩種解決方案:

  1. 在設置期間手動取整值;

  2. 如果有人試圖設置非整數部分量化,則拋出異常;

也許有人會給我一個建議什麼是寫這樣的代碼的最佳做法。也許GenericTypes適合這種情況?

+1

如果你需要基於類型的完全不同的行爲,也許你想讓Quant成爲一個類,然後繼承它的子類。只是一個想法。 –

回答

3

爲Quant的每個子類型創建單獨的類。提供需要IQuant接口,並調度使用dynamic特定類型覆蓋的方法:

interface IQuant { 
    QuantTypes QuantType { get; } 
} 
class QuantWeight { 
    public QuantTypes QuantType { 
     get { return QuantTypes.Weight; } 
    } 
    public double QuantWeightValue { get; } 
} 
class QuantCount { 
    public QuantTypes QuantType { 
     get { return QuantTypes.Pieces; } 
    } 
    public int PiecesValue { get; } 
} 

你的公開方法是這樣的:

public void ProcessQuant(IQuant quant) { 
    ProcessQuantImpl((dynamic)quant); 
} 
private void ProcessQuantImpl(QuantWeight weight) { 
    ... // Do the real work here 
} 
private void ProcessQuantImpl(QuantCount pieces) { 
    ... // Do the real work here 
} 
0

很抱歉,如果我做錯了。但我可以建議將「Quant」更改爲帶有所有計算的課程安裝基礎版本,然後使用不同的變量創建許多繼承類,然後使用諸如「quant.GetValue()」之類的內容。是否有意義?

+0

這基本上是@DangerZone提到的 – Artyom