子类的对象参考

时间:2019-05-28 19:19:41

标签: c#

namespace Test
{
    public class Program
    {
        static void Main(string[] args)
        {
            TestClass testC = new TestClass();
            testC.AssignRec(10);
            //testC.root - this is null 
        }
    }

    public class TestClass
    {
        public Childclass root;
        public void Assign(int data)
        {
           AssigRec(this.root,data);
        }
        public void AssignRec(Childclass rootnode, int data)
        {
            if (rootnode == null)
            {
                rootnode = new Childclass(data);
            }
        }
    }

    public class Childclass
    {
        public int data;
        public Childclass(int data)
        {
            this.data = data;
        }
    }
}

更新了子级参数名称。 在ChildClass内为子类TestClass分配值,但是在分配后,如果我尝试访问Childcalss值,则为null。不知道原因。

2 个答案:

答案 0 :(得分:3)

您必须将“ new ChildClass(data)”分配给当前实例的根。为此,您需要将新对象分配给“ this.root”。如下所示对TestClass进行更改:

    public class TestClass
    {
        public Childclass root;

        public void Assign(Childclass root, int data)
        {
            if (root == null)
            {
                //over here
                this.root = new Childclass(data);
            }
        }
    }

答案 1 :(得分:1)

当参数的名称与字段名称完全相同时,我们必须小心,因为在方法内部,除非使用this.root指定字段,否则名称将引用参数。

因此,代码的作用是分配类字段root ,仅当参数 root null

相反,如果后备字段为null,则似乎要执行分配,在这种情况下,您将执行以下操作:

    public void AssignRec(Childclass root, int data)
    {
        // Assign the field 'root' to the argument passed to this method unless the argument
        // to this method is 'null', in which case assign a new instance of ChildClass
        this.root = root ?? new ChildClass(data);
    }

虽然作为此类的使用者,但是如果我调用Assign方法并传递一些data却没有任何反应(如果类字段为{ {1}}不是root)。

我还对同时接受null ChildClass的方法感到困惑,因为尚不清楚两者之间的关系这些论据是。

相反,我建议提供两个重载,每个重载都有一个参数:

data