为什么IEquatable T不是在T为C#4.0做反向变换? [英] Why was IEquatable T not made contravariant in T for C# 4.0?

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

问题描述

IEquatable 可能已经被声明为在T中是逆变的,因为它仅在输入位置中使用T(或者,等价地,U是T的子类型应该意味着IEquatable T是[IEquatable U的子类型])。 / p>

所以,为什么BCL团队不使用'in'关键字注释它(对于C#4.0),因为它们与许多其他通用接口(如完全类似的IComparable )?

解决方案

我认为这主要是为了哲学的原因而不是技术限制–因为它完全可能,接口。 IEquatable< T> 意在比较相同类型的对象的精确相等性。超类的实例通常不等于子类的实例。在这个意义上的平等意味着类型相等。这与 IComparable< in T> 有点不同。可以在不同类型之间定义相对排序顺序。



引用 上的MSDN页面




实施者注意事项:



IEquatable< T> 接口的类型参数替换为 c> c> c> ; T> 意味着在单个具体类型的实例之间工作。


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>).

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)?

解决方案

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.

To quote MSDN page on IEquatable<T>:

Notes to Implementers:

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

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

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

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