将具体类型的 ICollection 转换为具体类型接口的 ICollection

Casting ICollection of a concrete type to an ICollection of the concrete type interface

Bar 实现 IBar 的情况下,将 ICollection<Bar> 转换为 ICollection<IBar> 的推荐方法是什么?

是不是像

一样简单
collection = new List<Bar>();
ICollection<IBar> = collection as ICollection<IBar>?

或者有更好的方法吗?

您必须转换列表中的每个项目并创建一个新项目,例如 Cast:

ICollection<IBar> ibarColl = collection.Cast<IBar>().ToList();

在 .NET 4 中,使用 IEnumerable<T> 的协方差:

ICollection<IBar> ibarColl = collection.ToList<IBar>();

List.ConvertAll:

ICollection<IBar> ibarColl = collection.ConvertAll(b => (IBar)b);

后者可能会更有效一些,因为它事先知道大小。

只需将所有条目转换为

ICollection<IBar> ibars = collection.ConvertAll(bar => (IBar)bar);

我觉得这个变体也是可读的。也许有办法让它具有更高的性能...

您不能转换为 ICollection<IBar>,但可以转换为 IEnumerable<IBar>

因此,如果您不打算向列表中添加内容,您可以这样做:

IEnumerable<IBar> enumeration = (IEnumerable<IBar>)collection;

其他答案的解决方案实际上并没有转换,而是创建了一个新列表,该列表不会反映对原始列表的后续更改。