我不知道我做错了什么。我有这段代码:
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)
为什么?
我一直在寻找答案,但我一无所获。
最佳答案
啊,可变结构的乐趣。正如 Sergey 所说,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;
关于C# 反射不适用于 Point 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24654888/