Recursive class C#

2019-06-05 00:06发布

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

2条回答
来,给爷笑一个
2楼-- · 2019-06-05 00:39

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);
    }
}
查看更多
Emotional °昔
3楼-- · 2019-06-05 00:57

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

查看更多
登录 后发表回答