【问题标题】:Recursive class C#递归类 C#
【发布时间】:2013-02-13 13:14:26
【问题描述】:

我可以这样定义构造函数吗?附加问题:我可以在自己的构造函数中调用类的构造函数吗?

class SubArray
{
    List<int> array;
    string parent;
    string name;
    SubArray child;

    public SubArray(SubArray child, string name)
    {
        this.child = child;
        List<int> array = new List<int>();
        this.name = name;
    }
}

【问题讨论】:

  • 在您提供的代码示例中,您NOTSubArray 的构造函数中调用SubArray 的构造函数。
  • 我知道。这是一个额外的问题
  • 你为什么要这样做?
  • 你试过了吗?结果是什么?另外你想做什么,添加新的子数组对象并设置它们的属性或替换一个对象中的现有属性?
  • 至少将递归部分委托给不同的方法调用。构造函数不应执行长时间运行的操作。

标签: c# oop class recursion


【解决方案1】:

对此没有限制,但就像任何递归一样 - 它需要一个停止条件。否则会导致堆栈溢出(PUN 意图:))。

【讨论】:

  • 对双关语的额外赞誉。 :)
【解决方案2】:

我猜你可以做这样的事情并且没有......明显的问题:

public SubArray(SubArray child, string name)
{
    this.child = child;
    this.array = new List<int>();
    this.name = name;

    if (child != null && child.child != null)
    {
        this.child.child = new SubArray(child.child,name);
    }
}

【讨论】:

    猜你喜欢
    • 2012-12-28
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-11
    • 2017-07-26
    • 2021-07-10
    相关资源
    最近更新 更多