为什么Enumerable.All序列是空的返回true? [英] Why does Enumerable.All return true for an empty sequence?
问题描述
var strs = new Collection<string>();
bool b = strs.All(str => str == "ABC");
的code创建字符串空集合,然后试图确定是否集合中的所有元素是ABC。
如果你运行它, B
将是真实的。
但集合甚至没有在任何元素,更不用说等于任何元素ABC。
But the collection does not even have any elements in it, let alone any elements that equal to "ABC".
这是一个错误,或者是有一个合理的解释?
Is this a bug, or is there a reasonable explanation?
推荐答案
这当然不是一个错误。它的表现究竟如记录:
It's certainly not a bug. It's behaving exactly as documented:
真正或如果序列为空;否则为false。
true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.
现在,你可以争论它是否应的工作方式(它似乎没什么问题;该序列的每个元素符合predicate),但的第一个事来检查的你问的东西之前是否是一个错误,是文档。 (这是要尽快检查作为一种方法比你预期的以外的行为方式的第一件事。)
Now you can argue about whether or not it should work that way (it seems fine to me; every element of the sequence conforms to the predicate) but the very first thing to check before you ask whether something is a bug, is the documentation. (It's the first thing to check as soon as a method behaves in a way other than what you expected.)
这篇关于为什么Enumerable.All序列是空的返回true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!