有没有办法使用反射在struct实例上设置属性?

Vic*_*aru 48 c# reflection propertyinfo

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

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

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

我之前已经对课程进行了大量的反思,但这种方法运行良好.另外,我知道在处理结构时,如果设置字段,则需要使用FieldInfo.SetValueDirect,但我不知道PropertyInfo的等效项.

Jon*_*eet 69

rectangle正在装箱的价值- 但是你丢失了盒装价值,这就是被修改的价值.试试这个:

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

  • 顺便说一下,这是可变值类型之一的一个很好的例子. (6认同)
  • 只需确保您没有在循环中执行此操作(或者性能不是问题),尤其是在结构很大的情况下。:-) (2认同)
  • 使用 VB.net 的人应该使用以下示例: Dim _rectangle As New Rectangle() Dim _propertyInfo As PropertyInfo = GetType(Rectangle).GetProperty("Height") Dim boxed As ValueType = _rectangle _propertyInfo.SetValue(boxed, 5, Nothing ) _rectangle = DirectCast(boxed, Rectangle) (2认同)

Meh*_*dad 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
    }
}
Run Code Online (Sandbox Code Playgroud)

还有其他方法,而不是__makeref你可以使用的无证件(见System.TypedReference),但它们更痛苦.