如何返回集合的只读副本

Eri*_*tas 13 c# collections properties readonly

我有一个包含集合的类.我想提供一个返回集合内容的方法或属性.如果调用类可以修改单个对象,但我不希望它们在实际集合中添加或删除对象,这是可以的.我一直在将所有对象复制到一个新列表,但现在我想我可以将列表作为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>();
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

Joe*_*oey 26

你可以使用List(T).AsReadOnly():

return this.mylist.AsReadOnly()
Run Code Online (Sandbox Code Playgroud)

这将返回一个ReadOnlyCollection.

  • 当然,您需要将List <String>中的返回类型替换为ReadOnlyCollection <string>或ICollection <string>或IEnumrable <string> (2认同)