如何做一个参考type属性"只读" [英] How to make a reference type property "readonly"

查看:97
本文介绍了如何做一个参考type属性"只读"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类酒吧包含引用类型私有字段。我想在一个公共财产暴露,但我不希望该属性的消费者能够改变 ...但应可变内部由酒吧,即我不能让现场只读

I have a class Bar with a private field containing the reference type Foo. I would like to expose Foo in a public property, but I do not want the consumers of the property to be able to alter Foo... It should however be alterable internally by Bar, i.e. I can't make the field readonly.

所以,我想的是:

      private _Foo;

      public Foo 
      { 
         get { return readonly _Foo; } 
      }



...这当然是无效的。我可以返回(assumming这是 IClonable )的克隆,但是这不是明摆着给消费者。我应该改变属性的名称 FooCopy ??它应该是一个 GetCop​​yOfFoo 的方法呢?你认为什么最佳做法?谢谢!

...which is of course not valid. I could just return a clone of Foo (assumming that it is IClonable), but this is not obvious to the consumer. Should I change the name of the property to FooCopy?? Should it be a GetCopyOfFoo method instead? What would you consider best practice? Thanks!

推荐答案

这听起来像你从C常量++相当于后。这并不在C#存在。有没有表明消费者不能修改一个对象的属性的方式,但别的东西可以(假设变异成员都是公开的,当然)。

It sounds like you're after the equivalent of "const" from C++. This doesn't exist in C#. There's no way of indicating that consumers can't modify the properties of an object, but something else can (assuming the mutating members are public, of course).

您可以返回美孚的克隆的建议,也可能是的视图的到富,为的 ReadOnlyCollection还确实为集合。当然,如果你可以让不可变型,这将使​​生活更简单...

You could return a clone of the Foo as suggested, or possibly a view onto the Foo, as ReadOnlyCollection does for collections. Of course if you could make Foo an immutable type, that would make life simpler...

请注意,有制作的字段的只读,使物体本身不可变的有很大的区别。

Note that there's a big difference between making the field readonly and making the object itself immutable.

目前,该类型本身可以以两种方式改变的事情。它可以这样做:

Currently, the type itself could change things in both ways. It could do:

_Foo = new Foo(...);

_Foo.SomeProperty = newValue;

如果只需要能够做到第二,本场可能是只读的,但你仍然有的人撷取属性能够变异对象的问题。如果只需要做的第一,而实际上是已经不可改变或可以作出不可变的,你可以只提供其中仅具有吸气,你的属性会没事的。

If it only needs to be able to do the second, the field could be readonly but you still have the problem of people fetching the property being able to mutate the object. If it only needs to do the first, and actually Foo is either already immutable or could be made immutable, you can just provide a property which only has the "getter" and you'll be fine.

这是的非常重要的你理解改变字段的值(使它引用不同的区别实例)并改变该字段指的是对象的内容

It's very important that you understand the difference between changing the value of the field (to make it refer to a different instance) and changing the contents of the object that the field refers to.

这篇关于如何做一个参考type属性"只读"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆