gpt4 book ai didi

C# 反射不适用于 Point 类?

转载 作者:行者123 更新时间:2023-11-30 19:40:09 25 4
gpt4 key购买 nike

我不知道我做错了什么。我有这段代码:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com