使对象在运行时不可变 [C#]

发布于 2024-07-26 19:26:28 字数 180 浏览 4 评论 0原文

有什么方法(我希望利用反射)可以使实例化对象及其所有公共属性不可变? 我有一个来自其他人的代码库(没有可用源)的类,我需要使用它,并且我基本上希望在实例化该类后,如果任何地方的任何代码段尝试调用该类中的公共设置器,则抛出异常。

注意:我不想在类周围创建包装对象来实现这一点。 我很懒。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

我还不会笑 2024-08-02 19:26:28

我很难相信您愿意引入反射代码来做一些可以通过包装类简单解决的事情。

现在,当您的反射代码损坏或需要修改时,您现在投入的一小部分时间将为您节省大量痛苦的时间。 包装类简单、易于实现、类型安全,并且对其他开发人员有意义。 不要让懒惰决定您的架构选择。

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.

离线来电— 2024-08-02 19:26:28

不,没有通过反射。 类型定义无法在运行时通过反射进行更改,因此它不能用作使类型不可变的设备。

但反射可用于违反类型的不变性。 例如,可以在构造函数运行很久之后通过反射设置标记为只读的属性。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文