c# - 从模板类转换

标签 c# templates inheritance interface

我有课MyClass<T>哪里T是一些接口(interface):

class MyClass<T> where T: IMyInterface

我编写了几个扩展 MyClass 的类使用IMyInterface的一些实现,例如:

class MySecondClass : MyClass<MyInterfaceImplementation>

为什么分配MySecondClass类型为 MyClass<IMyInterface> 的变量的实例不允许吗?

MyClass<IMyInterface> x = new MySecondClass()

当我添加隐式转换时:

public static implicit operator MyClass<IMyInterface>(MySecondClass c) {
    return c;
}

它开始工作。

最佳答案

要执行您想要的操作,您应该使用 out 关键字声明类型参数 T 是协变的(请参阅 MSDN 上的 Covariance and Contravariance in Generics)。
您需要稍微修改一下代码,因为协变和逆变只能在接口(interface)上定义:

interface IMyInterface { 
}

// note that this one is an interface now
interface IMyClass<out T> where T : IMyInterface { 
}

class MyInterfaceImplementation : IMyInterface { 
}

class MySecondClass : IMyClass<MyInterfaceImplementation> { 
}

class Program {
    static void Main(string[] args) {
        IMyClass<IMyInterface> x = new MySecondClass();
    }
}

关于c# - 从模板类转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19767117/

相关文章:

c# - 我什么时候应该单独实现 IEnumerator<T>?

c# - 有没有一种简洁的方法来实现TimeSpan格式的条件复数化?

c# - 存储网站登录凭据的最佳方法

c# - 通过 C# 将 Sitecore 项目 Url 设置为第三方服务器

c++ - 使用模板模板参数时出错

c++ - C++ 模板特化中声明的范围

inheritance - 转到 : How to reference a field in an inherited struct

c++ - 比较迭代器与 ptrdiff

c++ - 以成员函数启动线程(带继承)

c++ - 基于公共(public)参数调用某些类的构造函数c++