与对象分配的反射

时间:2017-11-23 22:21:14

标签: c# .net

为什么这个代码打印""而不是" newname"?我认为所有对象都是引用。我在这里缺少什么?

我知道我可以使用info [0] .SetValue ..但是我对一个包含对象数组的Property做了同样的事情,我想得到一个对象并给它一个新值。

    private void ()
    {
        A var1 = new A() { holder = new B() { name = "" }  };

        PropertyInfo[] info = var1.GetType().GetProperties();

        object obj1 = info[0].GetValue(var1); // this returns me A.holder object 

        B var2 = new B() { name = "newname" };

        obj1 = (object)var2; 

        Console.WriteLine(var1.holder.name);

    }

    public class B
    {
        public string name { get; set; }
    }

    public class A
    {
        public B holder { get; set; }
    }

编辑:好的,我想我遇到了问题

为obj1分配一个新引用,doenst更改var1.holder的引用。 感谢

2 个答案:

答案 0 :(得分:1)

注释您的代码:

// create a new A object in memory and a variable called var1 that points to it
A var1 = new A() { name = "" };

// get the list of properties on the A class
PropertyInfo[] info = var1.GetType().GetProperties();

// create a variable called obj1 that points to the value of 
// the first property on the A object created above (I.e. the empty string ""),
object obj1 = info[0].GetValue(var1);

// create a new A object in memory and a variable called var2 that points to it
A var2 = new A() { name = "newname" };

// change the variable obj1 to point to the new A object 
// instead of the string it previously pointed to
obj1 = (object)var2;

// print the name property of the first A, which has not changed since creation
Console.WriteLine(var1.name);

所以你可以看到属性var1.name的值实际上没有变化。

答案 1 :(得分:0)

您有作业

A var1 = new A() { name = "" };

并且之后没有任何内容会在var1中更改name的值,因此控制台会打印""