如何将Collection <ConcreteType>作为Collection <Interface>返回?

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)

Meh*_*ari 6

C#3.0泛型是不变的.如果不创建新对象,则无法做到这一点.C#4.0引入了安全的协方差/逆变,无论如何都不会改变读/写集合(你的情况).


Cha*_*ion 6

只需将指甲定义为

Collection<INail>
Run Code Online (Sandbox Code Playgroud)

  • 这是一个解决方案,但如果您只想要一个Nail对象的集合,那么这是一个问题,因为实现INail的每个对象都可以添加到集合中. (2认同)
  • 我应该提到这些类是使用XmlSerializer序列化的,这就是为什么集合必须定义为Collection <Nail>而不是Collection <INail>. (2认同)