c# - 为什么 IEnumerable<T>.Max 不将 T 约束为 IComparable?

标签 c# linq generics

如果调用 .Max() IEnumerable<T> 上的扩展方法,并且其中的对象不实现 IComparable , 一个得到 System.ArgumentException: At least one object must implement IComparable.

为什么不 Max和类似的方法约束 T实现IComparable , 这样这个问题就可以在编译时而不是在运行时被捕获?

最佳答案

比较……很有趣。首先,您可以选择 IComparable<T>IComparable - 你会选择哪个?目前(通过 Comparer<T>.Default )它支持两者,但没有“这个那个”通用约束。

然后你得到Nullable<T>的问题;这已经“提升”了比较,所以它是否具有可比性取决于 T ;但同样,Comparer<T>.Default为我们处理这个问题( Nullable<T> 既没有实现 IComparable 也没有实现 IComparable<T> )。

加上;它节省了通用约束传播;一旦你在库代码中有这样的约束,它就会迅速感染所有上游调用代码,使其成为一个艰难的过程。

关于c# - 为什么 IEnumerable<T>.Max 不将 T 约束为 IComparable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1176584/

相关文章:

c# - 使用 WebClient 下载 torrent 文件,导致文件损坏

c# - 在 C# 中合并包含列表的字典

c# - 如何访问我的 LINQ 模型中的特定行?

c# - 使用泛型调用重载函数

java - 向上转换不会导致类型删除吗?

c# - 头脑 Storm : How to arrange DateTime to particular interval frame?

c# - 为什么 (int)(33.46639 * 1000000) 返回 33466389?

c# - 在构造函数中使用 Mapper.Initialize

c# - LINQ - 根据字段总和在集合中查找项目

C# 到 VB.Net : Why does this fail to compile when converted to VB?