13

我有一个包含集合的类。我想提供一个返回集合内容的方法或属性。如果调用类可以修改单个对象是可以的,但我不希望它们从实际集合中添加或删除对象。我一直在将所有对象复制到一个新列表中,但现在我想我可以将列表返回为 IEnumerable<>。

在下面的简化示例中,GetListC 是返回集合的只读版本的最佳方式吗?

public class MyClass
{
    private List<string> mylist;

    public MyClass()
    {
        mylist = new List<string>();
    }

    public void Add(string toAdd)
    {
        mylist.Add(toAdd);
    }

    //Returns the list directly 
    public List<String> GetListA 
    { 
        get
            {
            return mylist;
            }
    }

    //returns a copy of the list
    public List<String> GetListB
    {
        get
        {
            List<string> returnList = new List<string>();

            foreach (string st in this.mylist)
            {
                returnList.Add(st);
            }
            return returnList;
        }
    }

    //Returns the list as IEnumerable
    public IEnumerable<string> GetListC
    {
        get 
        {
            return this.mylist.AsEnumerable<String>();
        }

    }

}
4

4 回答 4

26

您可以使用List(T).AsReadOnly()

return this.mylist.AsReadOnly()

这将返回一个ReadOnlyCollection.

于 2009-05-12T17:31:50.233 回答
2

只需使用 ReadOnlyCollection 类,从 .NET 2.0 开始就支持它

于 2009-05-12T17:31:41.250 回答
0

使用通用 ReadOnlyCollection 类 ( Collection.AsReadOnly())。它不会复制任何在基础集合更改时可能会产生一些奇怪结果的对象。

        var foo = new List<int> { 3, 1, 2 };
        var bar = foo.AsReadOnly();

        foreach (var x in bar) Console.WriteLine(x);

        foo.Sort();

        foreach (var x in bar) Console.WriteLine(x);

但是,如果您不想要副本,那是最好的解决方案。

于 2009-05-12T17:36:45.173 回答
-2

我更喜欢返回 IEnumerable,但您不需要强制转换。做就是了

public IEnumerable<string> StringList { get { return myList; }

List<string>是一个IEnumerable<string>

于 2009-05-12T17:42:00.297 回答