簡體   English   中英

有沒有辦法使用反射在結構實例上設置屬性?

[英]Is there a way to set properties on struct instances using reflection?

我正在嘗試編寫一些代碼來設置結構上的屬性(重要的是它是結構上的屬性)並且它失敗了:

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 的等價物。

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 ),但它們更痛苦。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM