jam*_*lle 2 c# generics collections interface .net-2.0
我有一个具体的类,其中包含另一个具体类的集合.我想通过接口公开这两个类,但是我无法弄清楚如何将Collection <ConcreteType>成员公开为Collection <Interface>成员.
我目前正在使用.NET 2.0
下面的代码导致编译器错误:
无法将类型'System.Collections.ObjectModel.Collection <Nail>'隐式转换为'System.Collections.ObjectModel.Collection <INail>'
注释的演绎尝试给出了这个编译错误:
无法
通过引用转换,装箱转换,拆箱转换,换行转换或空类型转换将类型'System.Collections.ObjectModel.Collection <Nail>'转换为'System.Collections.ObjectModel.Collection <INail>'.
有没有办法将具体类型的集合公开为接口集合,还是需要在接口的getter方法中创建新集合?
using System.Collections.ObjectModel;
public interface IBucket
{
Collection<INail> Nails
{
get;
}
}
public interface INail
{
}
internal sealed class Nail : INail
{
}
internal sealed class Bucket : IBucket
{
private Collection<Nail> nails;
Collection<INail> IBucket.Nails
{
get
{
//return (nails as Collection<INail>);
return nails;
}
}
public Bucket()
{
this.nails = new Collection<Nail>();
}
}
Run Code Online (Sandbox Code Playgroud)
只需将指甲定义为
Collection<INail>
Run Code Online (Sandbox Code Playgroud)