Make Object Immutable at Runtime [C#]

爷,独闯天下 提交于 2019-12-06 09:52:36

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.

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.

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