我无法弄清楚我做错了什么。我有这个代码:
Point p = new Point();
//point is (0,0)
p.X = 50;
//point is (50,0)
PropertyInfo temp = p.GetType().GetProperty("X");
temp.SetValue(p, 100, null);
//and point is still (50,0)
MethodInfo tt = temp.GetSetMethod();
tt.Invoke(p, new object[] { 200 });
//still (50,0)
为什么?
我在寻找答案,但我什么也没找到。
答案 0 :(得分:6)
Point
是一个结构。当你调用PropertyInfo.SetValue
时,你正在取p
的值,装箱(复制值),修改盒子的内容......但是忽略它。
你可以仍然使用反射 - 但重要的是,你只想将它包装一次。所以这有效:
object boxed = p;
PropertyInfo temp = p.GetType().GetProperty("X");
temp.SetValue(boxed, 100, null);
Console.WriteLine(boxed); // {X=100, Y=0}
MethodInfo tt = temp.GetSetMethod();
tt.Invoke(boxed, new object[] { 200 });
Console.WriteLine(boxed); // {X=200, Y=0}
请注意,此不会更改p
的值,但您可以在之后再次将其取消包装:
object boxed = p;
property.SetValue(boxed, ...);
p = (Point) boxed;
答案 1 :(得分:2)
Point是一个结构,而不是一个类。它是一个值类型,它通过值传递。因此,当您将点传递给SetValue
方法时,将传递点的副本。这就是原始实例p
未更新的原因。