gpt4 book ai didi

c# - 使用协变/逆变实现的接口(interface)会产生编译时错误

转载 作者:太空宇宙 更新时间:2023-11-03 18:33:56 24 4
gpt4 key购买 nike

我实现了一个带有协变/逆变类型约束的接口(interface),编译器告诉我 '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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com