C# 如何在C中用抽象约束实例化泛型类#

C# 如何在C中用抽象约束实例化泛型类#,c#,generics,inheritance,type-constraints,C#,Generics,Inheritance,Type Constraints,我有以下课程: public abstract class ThingBase { } public class ThingA : ThingBase { } 以及以下通用类: public class ThingOwner<ThingType> where ThingType : ThingBase { } 公共类ThingOwner,其中ThingType:ThingBase{} 我想创建一个ThingOwner实例,如下所示: ThingOwner<ThingBa

我有以下课程:

public abstract class ThingBase { }

public class ThingA : ThingBase { }
以及以下通用类:

public class ThingOwner<ThingType> where ThingType : ThingBase { }
公共类ThingOwner,其中ThingType:ThingBase{}
我想创建一个ThingOwner实例,如下所示:

ThingOwner<ThingBase> thingOwner = new ThingOwner<ThingA>();
ThingOwner ThingOwner=新ThingOwner();
通过这段代码,我得到了以下错误:“无法将类型‘ThingOwner(ThingA)’隐式转换为‘ThingOwner(ThingBase)’”

我不知道该怎么做。我知道有很多关于泛型类和继承的讨论,但是我几乎尝试了所有的方法,但我找不到一个适合我的解决方案


谢谢

协方差/逆变仅支持接口。如果需要类,则只有这些类可以工作:

ThingOwner<ThingBase> thingOwner = new ThingOwner<ThingBase>();
ThingOwner<ThingA> thingOwner = new ThingOwner<ThingA>();
ThingOwner ThingOwner=新ThingOwner();
ThingOwner ThingOwner=新ThingOwner();
您应该使用C#4.0中引入的。要使其工作,您需要使用接口而不是类:

public interface IThingOwner<out ThingType> where ThingType : ThingBase { }

public class ThingOwner<ThingType> : IThingOwner<ThingType>
    where ThingType : ThingBase
{

}


IThingOwner<ThingBase> thingOwner = new ThingOwner<ThingA>();
公共接口i ThingOwner,其中ThingType:ThingBase{}
公共类ThingOwner:i ThingOwner
where ThingType:ThingBase
{
}
i thingOwner thingOwner=新thingOwner();

除了上述答案之外,还有一些解释。虽然你的问题可以理解,但想想以下几点:


说明您有一个接受类型参数的派生类
ClassA
。在
ThingOwner
中,只允许添加属于或派生自
ClassA
的类的实例。当您将其转换为
ThingOwner
时,会突然允许添加
ClassB
的实例,该实例也派生自
BaseClass
。这可能会损害您的程序,实际上是错误的。这就是为什么他们一开始就发明了仿制药。

你的复制品救了我一周!非常感谢。