C#反射不适用于Point类?

use*_*501 2 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)
Run Code Online (Sandbox Code Playgroud)

为什么?

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

Jon*_*eet 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}
Run Code Online (Sandbox Code Playgroud)

请注意,这不会更改值p,但您可以在之后再次将其取消:

object boxed = p;
property.SetValue(boxed, ...);
p = (Point) boxed;
Run Code Online (Sandbox Code Playgroud)