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