C#反射不适用于Point类?

时间:2014-07-09 13:21:49

标签: c# reflection properties point

我无法弄清楚我做错了什么。我有这个代码:

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)

为什么?

我在寻找答案,但我什么也没找到。

2 个答案:

答案 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未更新的原因。

建议阅读:Value and Reference Types