有没有一种方法可以使用反射设置结构实例的属性

本文关键字:设置 反射 结构 实例 属性 可以使 方法 一种 有没有 | 更新日期: 2023-09-27 17:58:52

我正试图编写一些代码来设置结构上的属性(重要的是它是结构上的一个属性),但它失败了:

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

Height值(由调试器报告)从未被设置为任何值——它保持在默认值0。

我以前在课堂上做过很多反思,效果很好。此外,我知道在处理结构时,如果设置字段,则需要使用FieldInfo.SetValueDirect,但我不知道PropertyInfo的等效项。

有没有一种方法可以使用反射设置结构实例的属性

rectangle的值被装箱,但随后您将丢失装箱的值,也就是正在修改的值。试试这个:

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

听说过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),但它们更痛苦。