简体   繁体   English

为什么不IEnumerable <T> .Max约束T是IC可比的吗?

[英]Why doesn't IEnumerable<T>.Max constrain T to be IComparable?

If one calls the .Max() extension method on an IEnumerable<T> , and the objects within do not implement IComparable , one gets System.ArgumentException: At least one object must implement IComparable. 如果在IEnumerable<T>上调用.Max()扩展方法,并且其中的对象不实现IComparable ,则会获得System.ArgumentException: At least one object must implement IComparable.

Why don't Max and similar methods constrain T to implement IComparable , so that this problem can be caught at compile time instead of at run time? 为什么Max和类似方法没有约束T来实现IComparable ,所以这个问题可以在编译时而不是在运行时捕获?

Comparisons are... fun. 比较很有趣。 Firstly, you've got a choice of IComparable<T> or IComparable - which would you choose? 首先,您可以选择IComparable<T>IComparable - 您会选择哪个? Currently (via Comparer<T>.Default ) it supports both, but there is no "this or that" generic constraint. 目前(通过Comparer<T>.Default )它支持两者,但没有“this that”通用约束。

Then you get the issue of Nullable<T> ; 然后你得到Nullable<T>的问题; this has "lifted" comparisons, so whether it is comparable or not depends on the T ; 这已经“解除”了比较,所以它是否具有可比性取决于T ; but again, Comparer<T>.Default deals with this for us ( Nullable<T> implements neither IComparable nor IComparable<T> ). 但同样, Comparer<T>.Default为我们处理了这个问题( Nullable<T>既不实现IComparable也不实现IComparable<T> )。

Plus; 加; it saves on generic constraint propagation; 它节省了通用约束传播; as soon as you have a constraint like this in library code, it quickly infects all the upstream calling code, making it a hard slog. 一旦你在库代码中有这样的约束,它就会迅速感染所有上游调用代码,使其成为一个艰难的过程。

I guess because it's more flexible. 我想因为它更灵活。 For example, you may have an IEnumerable<object> which happens to contain strings, in which case Max() can be called quite safely on it, despite the fact that the type Object does not implement IComparable . 例如,您可能有一个碰巧包含字符串的IEnumerable<object> ,在这种情况下,可以非常安全地调用Max() ,尽管Object类型没有实现IComparable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM