How to set value of property where there is no setter

前端 未结 2 525
礼貌的吻别
礼貌的吻别 2020-12-06 17:34

I have seen various questions raised and answered where we can invoke a private setter using reflection such as this one:

Is it possible to get a property's priv

相关标签:
2条回答
  • 2020-12-06 18:08

    You have to keep in mind that a property is just syntactic sugar for a pair of methods. One method (the getter) returns a value of the property type and one method (the setter) accepts a value of the property type.

    There is no requirement that the getter and setter actually get or set anything. They're just methods, so they're allowed to do anything. The only requirement is that the getter return a value. From the outside there's no way you can really tell if there is a backing field. The getter could be getting computed every time it's called. It may be based on other properties.

    So, no, there isn't really any way in general to "set" a property that doesn't have a setter.

    0 讨论(0)
  • 2020-12-06 18:32

    I do not suggest doing this on your application but for testing purpose it may be usefull...

    Assuming you have:

    public class MyClass
    {
         public int MyNumber {get;}
    }
    

    You could do this if its for test purpose, I would not suggest to use this in your runtime code:

    var field = typeof(MyClass).GetField("<MyNumber>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic);
    field.SetValue(anIstanceOfMyClass, 3);
    
    0 讨论(0)
提交回复
热议问题