最佳实践:如何公开一个只读的ICollection [英] Best practice: How to expose a read-only ICollection

查看:160
本文介绍了最佳实践:如何公开一个只读的ICollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的ICollection< T> 名为 FOOS 在我的课,我要公开为只读(请参见这个问题 )。我看到的接口定义,这似乎是恰当的...我的问题是这样的一个属性 .IsReadOnly :我怎么让它明显的类的消费者认为 FOOS 是只读的?

I have an ICollection<T> called foos in my class which I want to expose as read-only (see this question). I see that the interface defines a property .IsReadOnly, which seems appropriate... My question is this: how do I make it obvious to the consumer of the class that foos is read-only?

我不想依靠他们记住查询 .IsReadOnly 尝试一个没有实现的方法,例如前为。新增()。理想情况下,我想揭露 FOOS ReadOnlyCollection还< T> ,但它不执行的IList< T> 。我应该通过一种方法揭露调用,例如 GetReadOnlyFooCollection ,而不是通过属性?如果是这样,岂不混淆人谁再期望一个 ReadOnlyCollection还< T>

I don't want to rely on them remembering to query .IsReadOnly before trying a not-implemented method such as .Add(). Ideally, I would like to expose foos as a ReadOnlyCollection<T>, but it does not implement IList<T>. Should I expose foo via a method called, for example, GetReadOnlyFooCollection rather than via a property? If so, would this not confuse someone who then expects a ReadOnlyCollection<T>?

这是C#2.0,这样的扩展方法,如了ToList()不可...

This is C# 2.0, so extension methods like ToList() are not available...

推荐答案

我似乎已经在返回的IEnumerable 与克隆的对象尘埃落定。

I seem to have settled on returning IEnumerable with the objects cloned.

public IEnumerable<Foose> GetFooseList() {
   foreach(var foos in Collection) {
     yield return foos.Clone();
   }
}




  • 需要一个克隆方法在FOOS。

  • 这使得集合中没有变化。请记住,ReadOnlyCollection还是自内它可以在在另一篇文章的链接提到被改变的对象漏。

    This allows no changes in the collection. Remember that ReadonlyCollection is "leaky" since the objects inside it can be changed as mentioned in a link in another post.

    这篇关于最佳实践:如何公开一个只读的ICollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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