Access fields of a Struct in an Object with Reflection

前端 未结 1 1832
名媛妹妹
名媛妹妹 2021-02-07 17:50

I\'m trying to use reflection (ultimately on unknown at compile time) object which include struct. I\'ve got as far as TypedReference.MakeTypedRe

1条回答
  •  遇见更好的自我
    2021-02-07 18:40

    Frankly, there's no need whatsoever for TypedReference here - just a boxed struct should work fine:

        var amountField = obj.GetType().GetField("Amount");
        object money = amountField.GetValue(obj);
        var codeField = money.GetType().GetField("Code");
        codeField.SetValue(money, "XXX");
        amountField.SetValue(obj, money);
    

    However! I will advise you of a few things:

    • public fields instead of properties are not usually a good idea; that will often bite you later
    • mutable structs (i.e. structs that can be changed after creation) are almost never a good idea, and will bite even more often, and bite harder
    • combining mutable structs and public fields compounds it, but making it very problematic to change later

    0 讨论(0)
提交回复
热议问题