4
我讀過一些與我的問題有關的問題,但我發現他們非常具體到某些程序設計,所以我希望得到一些建議,在我自己的具體情況...如何在多個子類中返回不同的類型?
我工作在程序,它允許您基於節點圖來執行邏輯操作,例如,您有不同類型的節點; CostantNode和Addition節點,可以繪製兩個常量並將它們鏈接到加法節點,以便最後處理輸入並輸出結果。到目前爲止節點類有用於處理虛擬方法:
//Node Logic
public virtual float Process(Dictionary<Guid, Node> allNodes)
{
//Override logic on child nodes.
return Value;
}
這種方法其overrided每個推導節點類型,除了例如:
/// <summary>
/// We pass Allnodes in so the Node doesnt need any static reference to all the nodes.
/// </summary>
/// <param name="allNodes"></param>
/// <returns>Addition result (float)</returns>
public override float Process(Dictionary<Guid, Node> allNodes)
{
//We concatenate the different input values in here:
float Result = 0;
if (Input.Count >= 2)
{
for (int i = 0; i < Input.Count; i++)
{
var _floatValue = allNodes[Input[i].TailNodeGuid].Value;
Result += _floatValue;
}
Console.WriteLine("Log: " + this.Name + "|| Processed an operation with " + Input.Count + " input elements the result was " + Result);
this.Value = Result;
// Return the result, so DrawableNode which called this Process(), can update its display label
return Result;
}
return 0f;
}
到目前爲止,一切偉大的工作,直到我試圖實現一個Hysteris節點,它基本上應該評估一個輸入並返回TRUE或FALSE,這是因爲我需要返回一個布爾值而不是一個浮點值,因此我通過解析返回到Bool程序,但我希望能夠在特定的子節點中自定義Process()返回類型,並且節點將處理結果存儲在浮點變量我叫做價值這也是在海斯特里斯我需要節點的價值是真或假...
希望你們可以提供一些指導我如何解決這個問題,我還沒有深入便便。
在此先感謝。
嗯,你可以返回'System.Object'和使用類型轉換... – 2013-04-08 19:41:13
我讀到這個問題時首先想到的是:「這個人正面臨着一些嚴重的設計問題......」。也許你應該瞭解Liskov替代原則。 – Erik 2013-04-08 19:43:05
@Iker:你爲什麼要從同一個虛擬方法中返回一個'bool'或者'float'?調用代碼在設置爲處理「浮點」值時使用「bool」值做什麼?您可能需要兩個獨立的方法(在這種情況下,不需要多態性),或者您需要重新考慮整個設計。 – 2013-04-08 19:56:37