什么是回报的ICollection名单上的优势 [英] What is the advantage of return ICollection over List

查看:166
本文介绍了什么是回报的ICollection名单上的优势的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
什么是(的T)列表和集合(T)的?

我有一个静态类和吸气给我回列表收藏。现在,我已阅读并已被告知返回ICollection的,而不是名单。什么是使用公共静态的ICollection对公共静态列表的优势在哪里?

I have a static class and a getter to return my List Collection. Now I read and have been told to return ICollection rather than List. What is the advantage of using public static ICollection over public static List?

static class Storage
{
    private static List<string> store;

    static Storage()
    {
        store = new List<string>();
    }

    public static ICollection<string> getList
    {
        get
        {
            return store.AsReadOnly();
        }
    }

    public static void addString(string add)
    {
        store.Add(add);
    }

    public static void removeString(string remove)
    {
        store.Remove(remove);
    }

    public static void display()
    {
        foreach (String view in store)
        {
            Console.WriteLine(view);
        }
    }
}



}

}

推荐答案


  • 的IEnumerable< T> 提供了一个仅向前的访问光标在一系列 T 的对象

  • 的ICollection< T> 提供同的IEnumerable< T> 也有计数属性(意指收集有一个明确的结束)

  • 的IList< T> 提供相同的的ICollection< T> 而且还随机存取通过索引列表中的任何元素(列表[5]

  • IEnumerable<T> provides access to a forward only cursor over a series of T objects
  • ICollection<T> provides the same as IEnumerable<T> but also a Count property (meaning the collection has a definitive end)
  • IList<T> provides the same as ICollection<T> but also random access to any element within the list via an indexer (list[5])
  • 列表< T> 实现上述所有的

    使用更简单的接口作为参数或者返回的好处价值在于,它提供了更多的灵活性,以呼叫者并且可以帮助记录如何对象将被使用(或拟在一个返回值的情况下使用)。

    The benefit of using a simpler interface as an argument or return value is that it gives more flexibility to the caller and can help to document how the object will be used (or is intended to be used in the case of a return value).

    这篇关于什么是回报的ICollection名单上的优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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