Recursive class C#

我的未来我决定 提交于 2020-01-03 03:12:07

问题


Can I define constructor like this? Additional question: Can I call constructor of the class in itself constructor?

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;
    }
}

回答1:


There is no limit on that, but like any recursion - it needs a stopping condition. otherwise it will cause a stack overflow (PUN intended :)).




回答2:


I guess you could do something like this and there is no....apparent problem:

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);
    }
}


来源:https://stackoverflow.com/questions/14854449/recursive-class-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!