简体   繁体   English

ReadOnlyCollection或IEnumerable用于公开成员集合?

[英]ReadOnlyCollection or IEnumerable for exposing member collections?

Is there any reason to expose an internal collection as a ReadOnlyCollection rather than an IEnumerable if the calling code only iterates over the collection? 如果调用代码只迭代集合,是否有任何理由将内部集合公开为ReadOnlyCollection而不是IEnumerable?

class Bar
{
    private ICollection<Foo> foos;

    // Which one is to be preferred?
    public IEnumerable<Foo> Foos { ... }
    public ReadOnlyCollection<Foo> Foos { ... }
}


// Calling code:

foreach (var f in bar.Foos)
    DoSomething(f);

As I see it IEnumerable is a subset of the interface of ReadOnlyCollection and it does not allow the user to modify the collection. 正如我所看到的,IEnumerable是ReadOnlyCollection接口的一个子集,它不允许用户修改集合。 So if the IEnumberable interface is enough then that is the one to use. 因此,如果IEnumberable接口足够,那么就是要使用的接口。 Is that a proper way of reasoning about it or am I missing something? 这是推理它的正确方法还是我错过了什么?

Thanks /Erik 谢谢/ Erik

More modern solution 更现代的解决方案

Unless you need the internal collection to be mutable, you could use the System.Collections.Immutable package, change your field type to be an immutable collection, and then expose that directly - assuming Foo itself is immutable, of course. 除非您需要内部集合是可变的,否则您可以使用System.Collections.Immutable包,将您的字段类型更改为不可变集合,然后直接公开它 - 假设Foo本身是不可变的,当然。

Updated answer to address the question more directly 更新的答案更直接地解决问题

Is there any reason to expose an internal collection as a ReadOnlyCollection rather than an IEnumerable if the calling code only iterates over the collection? 如果调用代码只迭代集合,是否有任何理由将内部集合公开为ReadOnlyCollection而不是IEnumerable?

It depends on how much you trust the calling code. 这取决于您对调用代码的信任程度。 If you're in complete control over everything that will ever call this member and you guarantee that no code will ever use: 如果您完全控制将要调用此成员的所有内容,并且您保证不会使用任何代码:

ICollection<Foo> evil = (ICollection<Foo>) bar.Foos;
evil.Add(...);

then sure, no harm will be done if you just return the collection directly. 那么肯定,如果你直接退回收藏品,不会造成任何伤害。 I generally try to be a bit more paranoid than that though. 我通常会尝试比这更偏执。

Likewise, as you say: if you only need IEnumerable<T> , then why tie yourself to anything stronger? 同样,如你所说:如果你只需要 IEnumerable<T> ,那么为什么要把自己绑在更强的东西上?

Original answer 原始答案

If you're using .NET 3.5, you can avoid making a copy and avoid the simple cast by using a simple call to Skip: 如果您使用的是.NET 3.5,则可以通过使用对Skip的简单调用来避免复制避免简单的转换:

public IEnumerable<Foo> Foos {
    get { return foos.Skip(0); }
}

(There are plenty of other options for wrapping trivially - the nice thing about Skip over Select/Where is that there's no delegate to execute pointlessly for each iteration.) (还有很多其他选项可以轻松包装 - Skip Select / Where的好处就是没有委托可以为每次迭代毫无意义地执行。)

If you're not using .NET 3.5 you can write a very simple wrapper to do the same thing: 如果您不使用.NET 3.5,您可以编写一个非常简单的包装器来执行相同的操作:

public static IEnumerable<T> Wrapper<T>(IEnumerable<T> source)
{
    foreach (T element in source)
    {
        yield return element;
    }
}

If you only need to iterate through the collection: 如果您只需要遍历集合:

foreach (Foo f in bar.Foos)

then returning IEnumerable is enough. 然后返回IEnumerable就足够了。

If you need random access to items: 如果您需要随机访问项目:

Foo f = bar.Foos[17];

then wrap it in ReadOnlyCollection . 然后将它包装在ReadOnlyCollection中

If you do this then there's nothing stopping your callers casting the IEnumerable back to ICollection and then modifying it. 如果你这样做,那么没有什么能阻止你的调用者将IEnumerable转换回ICollection然后修改它。 ReadOnlyCollection removes this possibility, although it's still possible to access the underlying writable collection via reflection. ReadOnlyCollection消除了这种可能性,尽管仍然可以通过反射访问底层的可写集合。 If the collection is small then a safe and easy way to get around this problem is to return a copy instead. 如果集合很小,那么解决此问题的一种安全且简单的方法是返回副本。

I avoid using ReadOnlyCollection as much as possible, it is actually considerably slower than just using a normal List. 我尽量避免使用ReadOnlyCollection,它实际上比使用普通List慢得多。 See this example: 看这个例子:

List<int> intList = new List<int>();
        //Use a ReadOnlyCollection around the List
        System.Collections.ObjectModel.ReadOnlyCollection<int> mValue = new System.Collections.ObjectModel.ReadOnlyCollection<int>(intList);

        for (int i = 0; i < 100000000; i++)
        {
            intList.Add(i);
        }
        long result = 0;

        //Use normal foreach on the ReadOnlyCollection
        TimeSpan lStart = new TimeSpan(System.DateTime.Now.Ticks);
        foreach (int i in mValue)
            result += i;
        TimeSpan lEnd = new TimeSpan(System.DateTime.Now.Ticks);
        MessageBox.Show("Speed(ms): " + (lEnd.TotalMilliseconds - lStart.TotalMilliseconds).ToString());
        MessageBox.Show("Result: " + result.ToString());

        //use <list>.ForEach
        lStart = new TimeSpan(System.DateTime.Now.Ticks);
        result = 0;
        intList.ForEach(delegate(int i) { result += i; });
        lEnd = new TimeSpan(System.DateTime.Now.Ticks);
        MessageBox.Show("Speed(ms): " + (lEnd.TotalMilliseconds - lStart.TotalMilliseconds).ToString());
        MessageBox.Show("Result: " + result.ToString());

Sometimes you may want to use an interface, perhaps because you want to mock the collection during unit testing. 有时您可能想要使用界面,可能是因为您想在单元测试期间模拟集合。 Please see my blog entry for adding your own interface to ReadonlyCollection by using an adapter. 请参阅我的博客条目 ,使用适配器将自己的接口添加到ReadonlyCollection。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 IEnumerable vs IReadonlyCollection vs ReadonlyCollection 用于公开列表成员 - IEnumerable vs IReadonlyCollection vs ReadonlyCollection for exposing a list member ReadOnlyCollection IEnumerable - ReadOnlyCollection IEnumerable 用于转换IQueryable的扩展方法 <T> 和IEnumerable <T> 到ReadOnlyCollection <T> - Extension methods for converting IQueryable<T> and IEnumerable<T> to ReadOnlyCollection<T> 私人清单 <T> 与公共IEnumerable <T> vs ReadOnlyCollection <T> - Private List<T> with public IEnumerable<T> vs ReadOnlyCollection<T> 类型“ System.Collections.Generic.IEnumerable”不包含成员“ Aggregate”,并且最佳扩展方法重载 - Type `System.Collections.Generic.IEnumerable' does not contain a member `Aggregate' and the best extension method overload 何时枚举集合(IEnumerable) - When are collections enumerated (IEnumerable) 动态创建 IEnumerable 集合 - Create IEnumerable collections dynamiclly 枚举本质上不是IEnumerable的集合? - Enumerating Collections that are not inherently IEnumerable? “Namespace.ClassName&#39;的成员访问&#39;DataType MemberName&#39;在类型&#39;System.Collections.Generic.IEnumerable`1 [Namespace.ClassName]上不合法。” - “Member access 'DataType MemberName' of 'Namespace.ClassName' not legal on type 'System.Collections.Generic.IEnumerable`1[Namespace.ClassName].” IEnumerable集合的串联C# - Concatenation of IEnumerable collections C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM