作者:0只0为0等0你0 | 来源:互联网 | 2022-12-07 13:29
几天前,我开始阅读C#手册.直到今天,除了这一点之外,我已经理解了大部分介绍的概念:
delegate T TestDelegate();
这行代码甚至没有编译,我知道这是因为返回类型不能逆变,我只是不明白为什么它不能这样.
1> Eric Lippert..:
Theodoros的答案是正确的.我喜欢思考这个问题的方法是问自己"假设这是合法的;可能会出错?"
delegate T D(); // Suppose this were legal.
class Animal {}
class Tiger : Animal {}
class Giraffe : Animal {} // Plainly all these are legal.
...
D da = () => new Tiger(); // A tiger is an animal, so this must be legal.
D dg = da; // This is legal because T is declared contravariant in D.
Giraffe g = dg(); // This is legal, because dg returns a giraffe.
// Except that it actually returns a tiger, and now we have a tiger in
// a variable of type giraffe.
除了第一行之外,该小程序片段中的每一行显然都是正确的.该程序不是类型安全的,因此必须是非法的.因此,我们必须得出结论,第一行必须是非法的,它是.