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