我正在尝试调用一个具有类似于以下定义的方法(已简化以避免混淆):
public static void Register<T>(T value) where T : BaseClass, IInterface
只要我有一个定义这两个值的类实例,它就可以正常工作。当我将“BaseClass”传递给一个方法然后尝试在上面的声明中使用该实例时,就会出现问题。例如:
public class MyClass
{
public MyClass(BaseClass value)
{
Register(value);
}
}
我可以将同时实现 BaseClass 和 IInterface 的类的实例传递给构造函数,但是当我尝试在 Register
方法中使用该值时,我得到一个编译错误,指出:
The type 'BaseClass' cannot be used as type parameter 'T' in the generic type or method 'Register(T)'. There is no implicit reference conversion from 'BaseClass' to 'IInterface'.
如果我像这样更改构造函数中的类型:
public class MyClass
{
public MyClass(IInterface value)
{
Register(value);
}
}
我收到一条错误信息:
The type 'IInterface' cannot be used as type parameter 'T' in the generic type or method 'Register(T)'. There is no implicit reference conversion from 'IInterface' to 'BaseClass'.
这似乎有点像第 22 条军规。 有没有一种方法可以定义参数以指示它必须同时实现 BaseClass 和 IInterface?
最佳答案
在我写问题的时候,我想出了答案,我想我应该把它贴出来而不是删除问题。
我只需要重新定义类:
public class MyClass<T> where T : BaseClass, IInterface
{
public MyClass(T value)
{
Register(value);
}
}
关于c# - 具有多个约束的通用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13748601/