是否可以在不创建列表副本的情况下创建ReadOnlyCollection?由于元素可以被转换为它的基类,所以ReadOnlyCollection不应该返回具体类型,而是返回实现的接口。从例如创建ReadOnlyCollection <IDisposable>。列表<FileStream>
编辑1调整代码表明我需要返回IList以保持API兼容性。
public class Program : IDisposable
{
List<Program> Programs = new List<Program>();
public IList<IDisposable> Getter
{
get
{
var readOnly = new ReadOnlyCollection<IDisposable>(Programs);
return readOnly;
}
}
static void Main(string[] args)
{
}
public void Dispose()
{
}
}
这将不会编译的原因很明显,但没有例如
ReadOnlyCollectionCast<Program,IDisposable>
哪个会投射到吸气剂中的IDisposable?
有点更多的历史,我到了那里。我确实重构了一个班级,它确实拥有List<IDisposable>
作为班级成员。我需要更好地序列化数据容器中的具体类型。将私人字段从List<IDisposable>
更改为List<Program>
是没有问题的,但公共属性应保持不变,并且仍将返回IList<IDisposable>
作为只读列表。
新的ReadOnlyCollection(Programs.Cast ());不会编译,因为它期望IList 而不是IEnumerable 。因为IEnumerable已经是不可变的,所以具有某种意义。 –