53

我正在尝试编写一些代码来设置结构上的属性(重要的是它是结构上的属性)并且它失败了:

System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle();
PropertyInfo propertyInfo = typeof(System.Drawing.Rectangle).GetProperty("Height");
propertyInfo.SetValue(rectangle, 5, null);

高度值(由调试器报告)永远不会设置为任何值 - 它保持默认值 0。

我之前对课程进行了很多反思,并且效果很好。另外,我知道在处理结构时,如果设置字段,则需要使用 FieldInfo.SetValueDirect,但我不知道 PropertyInfo 的等价物。

4

2 回答 2

80

的值rectangle被装箱 - 但是你失去了装箱的值,这是正在修改的。试试这个:

Rectangle rectangle = new Rectangle();
PropertyInfo propertyInfo = typeof(Rectangle).GetProperty("Height");
object boxed = rectangle;
propertyInfo.SetValue(boxed, 5, null);
rectangle = (Rectangle) boxed;
于 2011-06-08T14:38:02.467 回答
14

听说过SetValueDirect吗?他们成功是有原因的。:)

struct MyStruct { public int Field; }

static class Program
{
    static void Main()
    {
        var s = new MyStruct();
        s.GetType().GetField("Field").SetValueDirect(__makeref(s), 5);
        System.Console.WriteLine(s.Field); //Prints 5
    }
}

除了未记录的方法之外__makeref,您还可以使用其他方法(请参阅参考资料System.TypedReference),但它们更痛苦。

于 2011-06-08T14:59:44.747 回答