我已经实现了具有协/逆类型约束的接口,并且编译器告诉我'Student' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'T' in the generic type or method 'UserQuery.IMail<T,U>'

据我所知,我正在满足这些要求。我究竟做错了什么?

class Person { public Person(){} }
class Student : Person { public Student(){} }
class MatureStudent : Student {public MatureStudent(){}}

interface IMail<in T, out U> where T : new() where U : new() {
    void Receive(T t);
    U Return();
}

class Mail<Student,MatureStudent> : IMail<Student,MatureStudent> {
    public void Receive(Student s) {}
    public MatureStudent Return() { return new MatureStudent(); }
}

最佳答案

问题是您也声明了Mail也是通用的-您已经设置了StudentMatureStudent类型参数。您只想要:

class Mail : IMail<Student,MatureStudent> {

关于c# - 具有协方差/协方差的已实现接口(interface)会生成编译时错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18208783/

10-09 20:36