[英]Why is Enumerable Min or Max inconsistent between collections of reference and value types?
When dealing with empty sequences, I was surprised to find out that the behavior for min or max is different depending on whether the source collection elements are of value type or of reference type : 在处理空序列时,我很惊讶地发现min或max的行为是不同的,具体取决于源集合元素是值类型还是引用类型 :
var refCollection = new object[0];
var valCollection = new int[0];
var nullableCollection = new int?[0];
var refMin = refCollection.Min(x => x); // null
var valMin = valCollection.Min(); // InvalidOperationException
var nullableMin = nullableCollection.Min(); // null
This difference of behaviors is nicely seen on .NET Core implementation of Enumerable extensions . 在Enumerable扩展的.NET Core实现中很好地看到了这种行为差异。
This, however, is not the case when looking at Jon Skeet's MinBy extension , for example, which throws on either case as I would have expected. 然而,当看到Jon Skeet的MinBy扩展时 , 情况就不是这样了 ,例如,正如我所预期的那样抛出任何一种情况 。
Doesn't the difference in behaviors just cause confusions? 行为上的差异不会导致混淆吗? Is there any benefit to returning
null
for collections of ref types? 为ref类型的集合返回
null
有什么好处吗?
It's worth bearing in mind that nullable types (both nullable value types and reference types) behave differently to non-nullable value types in general when it comes to Min
: a null
value is treated as "missing" in general, so it's not unreasonable for the result of "the minimum of only missing values" to be "the missing value". 值得注意的是,当涉及
Min
时,可空类型(可空值类型和引用类型)的行为与非可空值类型的行为不同:一般来说null
值被视为“缺失”,因此对于它来说并不是不合理的。 “最小缺失值”的结果为“缺失值”。
For example: 例如:
int?[] nullableInts = new int?[5]; // All values null
int? min = nullableInts.Min(); // No exception, min is null
nullableInts[3] = 2;
min = nullableInts.Min(); // No exception, min is 2
For non-nullable value types, there really isn't the option of indicating a "missing value" (unless the return type were changed to always be a nullable type), hence the exception... but this is reasonably easy to spot anyway, as for a non-nullable value type, the only situation where there isn't a minimum is when the source is empty. 对于不可为空的值类型,实际上没有指示“缺失值”的选项(除非返回类型被更改为永远是可空类型),因此例外......但是这很容易被发现对于不可为空的值类型,唯一没有最小值的情况是源为空时。
(It's possible that MinBy
should actually behave the same way :) (
MinBy
可能实际上应该以相同的方式表现:)
This is also consistent with the conversions in LINQ to XML: 这也与LINQ to XML中的转换一致:
XElement element = null;
int? x = (int?) element; // null
int y = (int) element; // Bang
Basically, it does make a certain amount of sense - no option would be consistent with everything. 基本上,它确实有一定的意义 - 没有选择与一切都是一致的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.