【问题标题】:C# reflection doesn't work with Point class?C# 反射不适用于 Point 类?
【发布时间】:2014-08-30 13:12:17
【问题描述】:

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

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)

为什么?

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

【问题讨论】:

  • 我知道这几乎是显而易见的。非常感谢你们。

标签: c# reflection properties point


【解决方案1】:

啊,可变结构的乐趣。正如谢尔盖所​​说,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;

【讨论】:

  • 或者你可以在调用SetValue时使用RuntimeHelpers.GetObjectValue(p)来控制拳击
  • @KonradKokosa:嗯,可能 :) 不能说我自己用过,我不确定它在这里会有什么用...
【解决方案2】:

Point 是一个结构,而不是一个类。它是一个值类型,它是按值传递的。因此,当您将点传递给SetValue 方法时,会传递点的副本。这就是为什么原始实例p 没有更新的原因。

推荐阅读:Value and Reference Types

【讨论】:

    猜你喜欢
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 1970-01-01
    • 2022-01-20
    • 2023-04-07
    • 2011-08-18
    相关资源
    最近更新 更多