在 C# 中是否可以使函数返回的对象不可变?
我正在编写一个函数,该函数返回对某些封装数据结构的对象的引用,并且我希望没有人能够使用该引用更改该对象,是否可以在 c# 中执行此操作?
I am writing a function that returns a reference to an object of some encapsulated data structure and I want nobody to be able to change the object using that reference, is it possible to do this in c#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您返回的对象是不可变的,那就可以正常工作。
如果没有,您可以返回一个仅公开只读属性的包装对象。
If the object that you are returning is immutable, that will work fine.
If not, you can return a wrapper object that only exposes read-only properties.
我看到的唯一方法是为此类型创建两个接口。一个接口只是只读的。然后该方法仅返回此只读接口的实例。
The only way I see is to create two interfaces for this type. One interface just being read only. Then the method just returns an instance of this readonly interface.
我不认为有任何内置的方法。 C# 似乎没有像 C++ 那样支持常量正确性。您可以将内部成员设为只读,这将是一个开始。但还有更多的事情要做。
您可以将类的所有成员函数设置为非修改器函数,并将所有数据成员属性设置为私有设置器。在实现属性的 getter 时,复制返回的任何类,并返回一个新实例,而不是返回对私有成员的引用。
一些其他类
{
// ....
当您调用复制构造函数时,您
必须非常小心,SomeOtherClass 的实现会进行深层复制。
即使在这一切之后,您也不能 100% 保证有人不会修改您的对象,因为用户可以通过反射侵入任何对象。
I don't think there is any built-in way. C# doesn't seem to have the same support for const-correctness that C++ does. You can make the internal members read-only, and that will be a start. But there is more to it than that.
You would make all member functions of your class non-mutator functions, and make all data members properties w/ private setters. When implementing the getters for the properties, copy any classes that come back, and return a new instance, rather than returning a reference to a private member.
class SomeOtherClass
{
// ....
}
You will have to be very careful that the implementation of SomeOtherClass does a deep copy when you call the copy constructor.
Even after all this, you can't 100% guarantee that someone won't modify your object, because the user can hack into any object via reflections.