ReadOnlyCollection还或IEnumerable的曝光会员藏品? [英] ReadOnlyCollection or IEnumerable for exposing member collections?

查看:152
本文介绍了ReadOnlyCollection还或IEnumerable的曝光会员藏品?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何理由,露出内部的集合作为一个ReadOnlyCollection还,而不是一个IEnumerable如果调用code只能通过集合迭代?

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?

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);

当我看到它的IEnumerable是ReadOnlyCollection还的接口的一个子集,它不允许用户修改集合。因此,如果IEnumberable接口是足够那么这就是一个使用。那是推理它还是我失去了一些东西?有道

As I see it IEnumerable is a subset of the interface of ReadOnlyCollection and it does not allow the user to modify the collection. So if the IEnumberable interface is enough then that is the one to use. Is that a proper way of reasoning about it or am I missing something?

感谢/埃里克·

推荐答案

(编辑)

是否有任何理由,露出内部的集合作为一个ReadOnlyCollection还,而不是一个IEnumerable如果调用code只能通过集合迭代?

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?

这取决于你有多少信任调用code。如果你是在完全控制,将以往任何时候都调用这个会员的一切,你的保证的,没有code将永远使用:

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.

同样,当你说:如果你只的需要的IEnumerable&LT; T&GT; ,那么为什么扎自己什么都强。

Likewise, as you say: if you only need IEnumerable<T>, then why tie yourself to anything stronger?

原来的答复

如果您使用的是.NET 3.5,可以避免制作副本的的避免简单的投用简单的调用跳过:

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:

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.)

如果你不使用.NET 3.5,你可以写一个非常简单的包装,以做同样的事情:

If you're not using .NET 3.5 you can write a very simple wrapper to do the same thing:

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

这篇关于ReadOnlyCollection还或IEnumerable的曝光会员藏品?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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