使对象在运行时不可变 [C#]
有什么方法(我希望利用反射)可以使实例化对象及其所有公共属性不可变? 我有一个来自其他人的代码库(没有可用源)的类,我需要使用它,并且我基本上希望在实例化该类后,如果任何地方的任何代码段尝试调用该类中的公共设置器,则抛出异常。
注意:我不想在类周围创建包装对象来实现这一点。 我很懒。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(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.
不,没有通过反射。 类型定义无法在运行时通过反射进行更改,因此它不能用作使类型不可变的设备。
但反射可用于违反类型的不变性。 例如,可以在构造函数运行很久之后通过反射设置标记为只读的属性。
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.