Access fields of a Struct in an Object with Reflection

前端 未结 1 742
一生所求
一生所求 2021-02-07 17:53

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:42

    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)
提交回复
热议问题