使对象不可变的,在运行时[C#] [英] Make Object Immutable at Runtime [C#]
问题描述
有什么办法(利用反射我希望),我可以做一个实例化的对象不可变的以及所有的公共属性?我从别人的codeBase的(没有可用的源代码),我需要利用我基本上是想如果有一块code的任何地方尝试之后,调用这个类中的公共setter方法的异常被抛出一类已被实例化。
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.
推荐答案
没有有通过反射不是。类型定义不能在经由反射运行时被改变,因此它不能被用来作为一个装置,使一个类型不可变的。
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.
这篇关于使对象不可变的,在运行时[C#]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!