Make Object Immutable at Runtime [C#]

这一生的挚爱 提交于 2019-12-22 12:01:50

问题


Is there any way (utilizing Reflection I hope) that I can make an instantiated object immutable along with all of its public properties? I have a class from someone else's codebase (no source available) that I need to utilize and I basically want an exception to be thrown if any piece of code anywhere tries to call a public setter within this class after it has been instantiated.

Note: I do not want to create a wrapper object around the class in order to implement this. I am lazy.


回答1:


No there is not via reflection. Type definitions cannot be altered at runtime via reflection and hence it cannot be used as a device to make a type immutable.

But reflection can be used to violate immutability of a type. For instance, it's possible to set properties marked with readonly via reflection long after the constructor has run.




回答2:


I find it hard to believe that you are willing to introduce reflection code to do something that can be simply solved with a wrapper class.

A small investment of your time now will save you lots of painful time later when your reflection code breaks or requires modification. A wrapper class is simple, easy to implement, is type-safe, and will make sense to other developers down the road. Don't let laziness dictate your architectural choices.



来源:https://stackoverflow.com/questions/1120999/make-object-immutable-at-runtime-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!