2017-03-17 147 views
0

是否可以在不创建列表副本的情况下创建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>作为只读列表。

回答

1

你可以随时使用Linq。 programs.Cast<IDisposable>()给你一个IEnumerable<IDisposable>

编辑: 如果你真的需要返回一个IList,但要真正返回一些只读集合:

return new ReadOnlyCollection<IDisposable>(programs.Cast<IDisposable>().ToList());

+0

新的ReadOnlyCollection (Programs.Cast ());不会编译,因为它期望IList 而不是IEnumerable 。因为IEnumerable已经是不可变的,所以具有某种意义。 –

0

如果您使用的接口无需铸造List如下所示:

List<IDisposable> programs = new List<IDisposable>(); 
programs.Add(new Program()); 

将其作为只读方式返回:

public IEnumerable<IDisposable> GetReadOlnly() 
{ 
    return programs.Skip(0); 
} 

要返回只读IList

public IList<IDisposable> GetReadOlnly() 
{ 
    return programs.AsReadOnly(); 
} 
+0

不错的主意,但我需要返回一个IList 在一个公共getter需要保持API compat原因。 –

+0

请参阅编辑。想法仍然是 – CodingYoshi

+0

问题是我没有一个IDisposable列表,而是一个具体类的列表。那就是问题所在。 –