为什么 C# (4.0) 不允许泛型类类型中的协变和逆变? [英] Why does C# (4.0) not allow co- and contravariance in generic class types?

查看:34
本文介绍了为什么 C# (4.0) 不允许泛型类类型中的协变和逆变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

造成这种限制的真正原因是什么?是否只是必须完成的工作?概念上很难吗?不可能吗?

What is the real reason for that limitation? Is it just work that had to be done? Is it conceptually hard? Is it impossible?

当然,不能在字段中使用类型参数,因为它们都是可读写的.但这不可能是答案,不是吗?

Sure, one couldn't use the type parameters in fields, because they are allways read-write. But that can't be the answer, can it?

提出这个问题的原因是我正在写一篇关于C# 4 中的方差支持的文章,我觉得我应该解释一下为什么它仅限于委托和接口.只是为了推翻举证责任.

The reason for this question is that I'm writing an article on variance support in C# 4, and I feel that I should explain why it is restricted to delegates and interfaces. Just to inverse the onus of proof.

更新:埃里克问了一个例子.

这个怎么样(不知道这是否有意义,但:-))

What about this (don't know if that makes sense, yet :-))

public class Lookup<out T> where T : Animal {
  public T Find(string name) {
    Animal a = _cache.FindAnimalByName(name);
    return a as T;
  }
}

var findReptiles = new Lookup<Reptile>();
Lookup<Animal> findAnimals = findReptiles;

在一个类中使用它的原因可能是类本身中保存的缓存.并且请不要给不同类型的宠物起相同的名字!

The reason for having that in one class could be the cache that is held in the class itself. And please don't name your different type pets the same!

顺便说一句,这让我想到了可选类型参数在 C# 5.0 中 :-)

BTW, this brings me to optional type parameters in C# 5.0 :-)

更新 2: 我不是说 CLR 和 C# 应该允许这样做.只是想了解是什么导致了它没有.

Update 2: I'm not claiming the CLR and C# should allow this. Just trying to understand what led to that it doesnt.

推荐答案

首先,正如 Tomas 所说,CLR 不支持它.

First off, as Tomas says, it is not supported in the CLR.

其次,这将如何运作?假设你有

Second, how would that work? Suppose you have

class C<out T>
{ ... how are you planning on using T in here? ... }

T 只能用于输出位置.正如您所注意到的,该类不能有任何 T 类型的字段,因为该字段可以被写入.该类不能有任何采用 T 的方法,因为这些方法是逻辑写入的.假设你有这个功能——你会如何利用它?

T can only be used in output positions. As you note, the class cannot have any field of type T because the field could be written to. The class cannot have any methods that take a T, because those are logically writes. Suppose you had this feature -- how would you take advantage of it?

如果我们可以让 T 类型的只读字段合法,那么这对不可变类很有用;这样我们就大大减少了它被错误写入的可能性.但是很难想出其他允许以类型安全方式变化的场景.

This would be useful for immutable classes if we could, say, make it legal to have a readonly field of type T; that way we'd massively cut down on the likelihood that it be improperly written to. But it's quite difficult to come up with other scenarios that permit variance in a typesafe manner.

如果你有这样的场景,我很乐意看到.这将有助于有一天在 CLR 中实现这一点.

If you have such a scenario, I'd love to see it. That would be points towards someday getting this implemented in the CLR.

更新:见

为什么是'C# 4.0 中的类是否存在通用差异?

有关此问题的更多信息.

for more on this question.

这篇关于为什么 C# (4.0) 不允许泛型类类型中的协变和逆变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆