c# - 具有多个约束的通用

标签 c# generics inheritance

我正在尝试调用一个具有类似于以下定义的方法(已简化以避免混淆):

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/

相关文章:

c# - 如何知道 virtual\override 中的大多数派生实现

c# - 并发队列性能不佳

c++ - 在类层次结构中初始化变量

postgresql - 如何在 PostgreSQL 9.2 中实现(或模拟)子类型多态性?

java - 从java中的枚举列表中删除一个元素

c++ - 一个类如何继承自己?

c# - Microsoft.Azure.Management.Api管理实现

c# - 在 FastReport 导出(如 PDF、Excel、rtf 等)中,并非所有页面都不会导出数据

c++ - 为什么我不能使用浮点值作为模板参数?

具有关联类型的 Swift 子协议(protocol)