【发布时间】:2018-03-25 13:09:40
【问题描述】:
我一直在学习 C# 中的协变和逆变,但有些东西我看不懂:
class Program
{
static void Main(string[] args)
{
PersonCollection<Person> personCollection = new PersonCollection<Person>();
IMyCollection<Teacher> myCollection = personCollection; // Here's the error:
// Cannot implicitly convert type 'PersonCollection<Teacher>' to 'IMyCollection<Person>'
}
}
class Person { }
class Teacher : Person { }
interface IMyCollection<T> { }
class PersonCollection<T> : IMyCollection<T> { }
众所周知,我们可以将派生类的实例隐式转换为基类。所以,在上面的代码中,虽然 'Teacher' 类是从 'Person' 类派生的,但 IMyCollection<Teacher> 不能转换为 IMyCollection<Person>,为什么?
注意:我想知道原因,而不是解决方案。
【问题讨论】:
-
继续阅读协变和逆变。这个问题就是这样
-
这就是泛型中的协变和逆变的意思。如果您在 IMyColletion 中将 T 声明为 Covariance,则可以将具有类型参数的类分配给具有基类类型参数声明的类
-
请参阅docs.microsoft.com/en-us/dotnet/standard/generics/… 中的列表。它的定义很好。
-
@JPVenson 我知道。我只是想知道我们不能正常做的原因
-
因为如果你会得到
myCollection中的第一个项目,你希望它是Teacher,但它也可能是一个人。
标签: c# generics inheritance