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

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

问题描述

var strs = new Collection<string>();
bool b = strs.All(str => str == "ABC");

代码创建一个空的字符串集合,然后尝试确定集合中的所有元素是否都是ABC".如果你运行它,b 将为真.

The code creates an empty collection of string, then tries to determine if all the elements in the collection are "ABC". If you run it, b will be true.

但该集合中甚至没有任何元素,更不用说任何等于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:

如果源序列的每个元素都通过了指定谓词中的测试,则为真,或者如果序列为空;否则为假.

true if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, false.

现在你可以争论它是否应该那样工作(对我来说似乎很好;序列的每个元素都符合谓词)但是首先要检查 在你问是否有问题之前,先看看文档.(当方法的行为与您预期的不同时,首先要检查它.)

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天全站免登陆