带有co / contravariance的已实现接口会生成编译时错误

时间:2013-08-13 12:12:19

标签: c#

我已经实现了一个带有co / contravariant类型约束的接口,编译器告诉我'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(); }
}

1 个答案:

答案 0 :(得分:7)

问题在于您宣布Mail也是通用的 - 您已经制作了StudentMatureStudent类型参数。你只想要:

class Mail : IMail<Student,MatureStudent> {