C# 反射不适用于 Point 类?

标签 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)

为什么?

我一直在寻找答案,但我一无所获。

最佳答案

啊,可变结构的乐趣。正如 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/

相关文章:

java - 在哪里可以找到 Class.getProtectionDomain().getCodeSource() 方法的规范?

java - 什么是反射,它为什么有用?

javascript - 我可以在 React.js 中更新组件的 props 吗?

c# - 将自动属性转换为通知属性(WPF 中的 MVVM)

c# - 将窄类型转换为宽类型以节省内存并保持高精度计算是不是一个糟糕的主意?

c# - 在 XML 序列化中包含数组索引

c# - 将字符串转换为日期时间

c# - 组合框值成员错误

java - 改为调用其他方法

ios - readwrite 和 readonly 互斥