为什么 IEquatable T 没有在 C# 4.0 的 T 中实现逆变? [英] Why was IEquatable T not made contravariant in T for C# 4.0?

查看:19
本文介绍了为什么 IEquatable T 没有在 C# 4.0 的 T 中实现逆变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IEquatable可能在 T 中被声明为逆变,因为它只在输入位置使用 T(或者,等效地,U 作为 T 的子类型应该意味着 IEquatable 是 [一个] IEquatable 的子类型).

IEquatable<T> could have been declared to be contravariant in T, since it only uses T in an input position (or, equivalently, U being a subtype of T should imply that IEquatable<T> is [a subtype of] IEquatable<U>).

那么,为什么 BCL 团队没有像对许多其他通用接口(例如完全类似的 IComparable)那样使用 'in' 关键字对其进行注释(对于 C# 4.0)?

So, why did the BCL team not annotate it (for C# 4.0) with the 'in' keyword, as they did with many other generic interfaces (like the entirely analogous IComparable)?

推荐答案

我认为这主要是出于哲学原因而不是技术限制——因为完全可以简单地对界面进行注释.IEquatable 用于比较相同类型的对象是否完全相等.超类的实例通常不被认为等同于子类的实例.这种意义上的平等也意味着类型平等.这与 IComparable 有点不同.定义跨不同类型的相对排序顺序是明智的.

I think this is mainly for a philosophical reason rather than a technical limitation–as it's perfectly possible to simply annotate the interface. IEquatable<T> is meant to compare objects of the same type for exact equality. An instance of a superclass is not usually considered equal to an instance of a subclass. Equality in this sense implies type equality too. This is a bit different from IComparable<in T>. It can be sensible to define a relative sort order across different types.

引用 IEquatable 上的 MSDN 页面:

To quote MSDN page on IEquatable<T>:

给实施者的注意事项:

IEquatable接口的类型参数替换为实现该接口的类型.

Replace the type parameter of the IEquatable<T> interface with the type that is implementing this interface.

这句话进一步证明了 IEquatable 旨在在单个具体类型的实例之间工作.

This sentence further demonstrates the fact that IEquatable<T> is meant to work between instances of a single concrete type.

这篇关于为什么 IEquatable T 没有在 C# 4.0 的 T 中实现逆变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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