【问题标题】:How to return different types on multiple child classes?如何在多个子类上返回不同的类型?
【发布时间】:2013-04-08 19:39:21
【问题描述】:

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

我正在开发一个程序,该程序允许您基于节点图进行逻辑操作,例如,您有不同类型的节点; 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 的浮点变量中,该变量也在歇斯底里我需要节点的值为 True 或 False...

希望你们能给我一些关于如何解决这个问题的指导,我没有深入研究过 POO。

提前致谢。

【问题讨论】:

  • 好吧,你可以返回 System.Object 并使用类型转换...
  • 当我读到这个问题时,我想到的第一件事是:“这家伙正面临一些严重的设计问题......”。也许你应该了解一下 Liskov 替换原则。
  • @Iker:为什么要从同一个虚拟方法返回boolfloat?当全部设置为处理float 值时,调用代码会对bool 值做什么?您要么需要两个单独的方法(在这种情况下不需要多态性),要么需要重新考虑整个设计。
  • @Christian Hayter 小视频让您了解该程序的工作原理...youtube.com/watch?v=bp24W3ebwAQ&feature=youtu.be

标签: c#


【解决方案1】:

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
}

【讨论】:

    猜你喜欢
    • 2022-11-15
    • 1970-01-01
    • 2011-01-22
    • 1970-01-01
    • 2012-07-05
    • 2013-05-14
    • 1970-01-01
    • 2016-04-30
    • 2013-07-07
    相关资源
    最近更新 更多