说,我们有一个带有私有List的泛型类。 我们可以使它至少以两种方式返回此列表的只读包装:
public class Test<T>
{
public List<T> list = new List<T>();
public IEnumerable<T> Values1
{
get
{
foreach (T i in list)
yield return i;
}
}
public IEnumerable<T> Values2
{
get
{
return list.AsReadOnly();
}
}
}
Values1
和Values2
都反映了基础集合中的任何字符,并阻止它自行修改。
哪种方式更可取?应该注意什么?或者还有其他更好的方法吗?
答案 0 :(得分:11)
如果输出只需要IEnumerable<T>
,我更喜欢:
public IEnumerable<T> Values
{
return this.list.AsReadOnly();
}
由于ReadOnlyCollection<T>
实现了IEnumerable<T>
,这为您的对象提供了一个安全的包装,同时仍然保持灵活和高效,并防止强制转换设置值。
如果您决定需要在结果中执行不同的操作,则可以随后更改内部实现。