如何在多个子类上返回不同的类型
本文关键字:返回 类型 子类 | 更新日期: 2023-09-27 18:08:11
我已经阅读了一些与我的问题相关的问题,但我发现它们非常具体到某些程序设计,所以我希望得到一些关于我自己的具体情况的建议…
我正在做一个程序,它允许你做基于节点图的逻辑运算,你有不同类型的节点,例如;CostantNode和Addition节点,您可以绘制两个常量并将它们链接到Addition节点,以便最后一个将处理输入并抛出结果。到目前为止,Node类有一个用于处理的Virtual方法:
//Node Logic
public virtual float Process(Dictionary<Guid, Node> allNodes)
{
//Override logic on child nodes.
return Value;
}
该方法在每个派生的nodeType上被重写,此外,例如:
/// <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()返回类型在特定的子节点,也,节点将处理结果存储在一个名为Value的浮点变量中,该变量也在Hysteris中,我需要节点的值为True或False…
希望你们能给我一些关于如何处理这个问题的指导,我还没有深入研究过POO。
c#没有多态返回值的概念。您必须返回一个包含两个值的结构:
struct ProcessResult
{
public float Value;
public bool Hysteresis;
}
ProcessResult Process(Dictionary<Guid, Node> allNodes)
{
var result = new ProcessResult();
// Assign value to result.Value
// Assign hysteresis to result.Hysteresis
// return result
}
或者使用类似于框架的TryParse模式的模式:
bool TryProcess(Dictionary<Guid, Node> allNodes, out float result)
{
// Assign value to result
// Return hysteresis
}