【发布时间】:2015-05-23 22:35:40
【问题描述】:
以这个小的 LINQPad 为例:
void Main()
{
Foo<object> foo = new Foo<string>();
Console.WriteLine(foo.Get());
}
class Foo<out T>
{
public T Get()
{
return default(T);
}
}
编译失败,出现这个错误:
无效的方差修饰符。只有接口和委托类型参数可以指定为变体。
我认为代码没有任何逻辑问题。一切都可以静态验证。为什么不允许这样做?它会导致语言上的一些不一致,还是由于 CLR 的限制而被认为实施起来过于昂贵?如果是后者,作为开发人员,我应该对上述限制了解什么?
考虑到接口支持它,我希望类支持从逻辑上遵循。
【问题讨论】:
-
@Stilgar:你能不能回答“因为底层 CLR 实现中的这个东西不支持它”?
-
@J...我当然读过手册。这仍然不能解释为什么它“会做很多工作”。如果是因为实现细节,最好至少了解一下该实现。
-
@J...:也许你对如何和为什么不感兴趣,但这并不意味着每个人都必须盲目地遵循手册而不质疑任何设计决策。虽然总的来说,对于诸如“为什么语言 X 不支持 Y?”之类的问题,最直接的实用答案确实是正确的。是“因为没有人指定/实现它。”,更好 的答案肯定总是提供解释,说明为什么它不像最初出现的那样好,如果有任何这样的解释可用。
-
我建议阅读 Erik Lippert 的Why Doesn't C# ...?,答案:
The answer is always the same: because no one ever designed, specified, implemented, tested, documented and shipped that feature. All six of those things are necessary to make a feature happen. All of them cost huge amounts of time, effort and money. Features are not cheap, and we try very hard to make sure that we are only shipping those features which give the best possible benefits to our users given ... -
@J... 那为什么它对接口有意义呢?您反对“狂野类型转换”的论点对我来说毫无意义。
标签: c# class generics generic-variance