c# - 如何在 C# 中实例化具有抽象约束的泛型类

标签 c# generics inheritance type-constraints

我有以下类(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/

相关文章:

c# - 无法在 sting c# 中编写脚本

c++ - 错误 : ‘length’ was not declared in this scope c++

c++ - 对 C++ 中的继承感到困惑(公共(public)和私有(private))

Java 泛型继承/泛型比较

c# - 使用 xval 客户端验证表单

c# - 如何检查 Logo /图像是否在图像中?

c# - 如何一般地格式化 OracleNumber

c# - 使用 Type 变量调用泛型方法

java - 从 FXML 设置 TableView 通用类型?

java - 为什么 Collection.toArray(T[]) 不采用 E[] 代替