I have a class in which a lot of properties. I need to dynamically change the attributes of some fields as soon as read. The fact is that the installation of this attribute depends on the input data. How to do it?
1 answer
You can check in the setter whether it is possible to set the current property, and if not, then, for example, throw an exception:
private int prop public int Prop { get { return prop;} set { if(canSetProp) prop = value; else throw new InvalidOperationException(); } } - oneIn vain you suggest this. Dynamic change of access to a property is a deeply flawed practice, since entails difficult-to-fix architectural flaws. - Bulson
- @Bulson, strictly speaking, there is no change in access to the property. In fact, in this case, the properties are used for their intended purpose: they allow you to add functionality before getting the value, or before setting the values. For simplicity, this can be considered the usual validation of input data. - Grundy
- well, someone or something will have access to this canSetProp
canSetPropand thereby become the implicit sovereign owner of access to this setter. Is not it so? - Bulson - one@Alexander Muksimov, in inept hands, anything will be a harmful invention. Puzzling Exception will not cause if the error text is clear. - Grundy
- oneWell, here we are called to chat and I think that we will not say anything new. I just think that children should be taught only good (including style) - they learn bad things themselves. - Alexander Muksimov
|
Settingclass, and simply assign the variable tonullornew Setting(), depending on whether you need a setting or not. This design seems more appropriate to me. - VladD