C# 将实现的泛型放入集合时出错

C# 将实现的泛型放入集合时出错,c#,generics,C#,Generics,像往常一样,我希望在代码中有泛型类型,以允许在不同的上下文中进行多次使用。作为一个例子,我构建了一个我想要的更简单的版本,它也有同样的问题 泛型类: class GenericBase<T> { public T item { get; } public GenericBase(T item) { this.item = item; } } class GenericOuter<T> { private rea

像往常一样,我希望在代码中有泛型类型,以允许在不同的上下文中进行多次使用。作为一个例子,我构建了一个我想要的更简单的版本,它也有同样的问题

泛型类:

class GenericBase<T>
{
    public T item { get;  }

    public GenericBase(T item)
    {
        this.item = item;
    }
}

class GenericOuter<T>
{
    private readonly GenericBase<T> single;
    private readonly ISet<GenericBase<T>> baseSet;

    public GenericOuter(GenericBase<T> single, ISet<GenericBase<T>> baseSet)
    {
        this.single = single;
        this.baseSet = baseSet;
    }
}
类GenericBase
{
公共T项{get;}
公共通用库(T项)
{
this.item=项目;
}
}
类通用计算机
{
专用只读GenericBase single;
专用只读ISet基集;
公共GenericOuter(GenericBase single,ISet baseSet)
{
这个。单身=单身;
this.baseSet=baseSet;
}
}
我想实现
GenericBase
如下:

class ConcreteBase : GenericBase<int>
{
    ConcreteBase(int item) : base (item) { }
}
class ConcreteOuter : GenericOuter<int>
{
    ConcreteOuter(ConcreteBase single, ISet<ConcreteBase> items) : base(single, items) { }
}
class-ConcreteBase:GenericBase
{
ConcreteBase(int项):base(项){}
}
这很好用。 我还想实现
GenericOuter
如下:

class ConcreteBase : GenericBase<int>
{
    ConcreteBase(int item) : base (item) { }
}
class ConcreteOuter : GenericOuter<int>
{
    ConcreteOuter(ConcreteBase single, ISet<ConcreteBase> items) : base(single, items) { }
}
class-ConcreteOuter:GenericOuter
{
ConcreteOuter(ConcreteBase single,ISet items):基本(single,items){}
}
问题是我遇到了以下错误:

CS1503: Argument 2: Cannot convert from 'System.Collections.Generic.ISet<namespace.ConcreteBase>' to 'System.Collections.Generic.ISet<namespace.GenericBase<int>>'
CS1503:参数2:无法从“System.Collections.Generic.ISet”转换为“System.Collections.Generic.ISet”
我不明白为什么它不起作用。这不是简单的类继承吗


它适用于参数1,参数1的类型相同,但不在一个集合中。

不,它们不是同一件事。假设您将创建第二个类
SecondConcreteBase:GenericBase
。您可以将其添加到
ISet
中,但不能添加到
ISet
,我希望这能说明为什么您不能将
ISet
强制转换为
ISet
,它们只是不同而已。如果你想知道更多关于实际发生的事情以及为什么某些强制类型转换被允许或不被允许,请查阅协方差、逆变和不变性。我理解你的意思。在某种程度上,我必须将类限制为某个类型,并且只接受该类型的一个实现。非常感谢。具有不变的泛型类型参数,因此它不起作用。您应该使用与类型参数完全相同的类型。具有协变类型参数,它可能适用于您的情况(尚未检查)