我有以下类(class):
public abstract class ThingBase { }
public class ThingA : ThingBase { }
还有下面的泛型类:
public class ThingOwner<ThingType> where ThingType : ThingBase { }
我想创建一个如下所示的 ThingOwner 实例:
ThingOwner<ThingBase> thingOwner = new ThingOwner<ThingA>();
使用此代码,我收到以下错误:“无法将类型‘ThingOwner(ThingA)’隐式转换为‘ThingOwner(ThingBase)’”。
我不知道如何让它发挥作用。我知道现在有很多关于泛型类和继承的讨论,但我几乎尝试了所有方法,但找不到适合我的解决方案。
谢谢!
最佳答案
你应该使用covariance for generic types在 C# 4.0 中引入。为此,您需要使用接口(interface)而不是类:
public interface IThingOwner<out ThingType> where ThingType : ThingBase { }
public class ThingOwner<ThingType> : IThingOwner<ThingType>
where ThingType : ThingBase
{
}
IThingOwner<ThingBase> thingOwner = new ThingOwner<ThingA>();
关于c# - 如何在 C# 中实例化具有抽象约束的泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21673300/