c# - 如何在多个子类上返回不同的类型?

标签 c#

我已经阅读了一些与我的问题相关的问题,但我发现它们非常特定于某些程序设计,所以我希望就我自己的具体情况获得一些建议......

我正在开发一个程序,它允许您基于节点图进行逻辑运算,例如,您有不同类型的节点; CostantNode 和 Addition 节点,您可以绘制两个常量并将它们链接到 Addition 节点,这样最后一个节点将处理输入并抛出结果。至此Node类有一个Virtual方法进行处理:

//Node Logic
    public virtual float Process(Dictionary<Guid, Node> allNodes)
    {
        //Override logic on child nodes.
        return Value;
    }

此方法在每个派生的 nodeType 上重写,例如在 Addition 中:

        /// <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 值而不是浮点值,我做了它通过在程序的 View 端解析 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
}

关于c# - 如何在多个子类上返回不同的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15887468/

相关文章:

c# - 就地清除的枚举扩展方法

c# - Windows 窗体中的多个用户

c# - 使用 MVVM 和 Prism 了解 Unity 和依赖注入(inject)

c# - Web API AuthorizeAttribute 不返回自定义响应

c# - WinForms 服务器和客户端之间的通信

c# - div 位置内的图像按钮

c# - 查询两个表中拥有所有请求记录的用户

c# - 如何自动创建一个与 Access 表兼容的类?

C# JSON DeserializeObject,不断获取 nullreference

c# - 如何检查字符串是否会触发 “A potentially dangerous Request.Form value was detected…” 错误