为什么Enumerable.All序列是空的返回true? [英] Why does Enumerable.All return true for an empty sequence?

查看:286
本文介绍了为什么Enumerable.All序列是空的返回true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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屋!

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