为什么Any()在C#空对象上不起作用 [英] Why doesn't Any() work on a c# null object

查看:107
本文介绍了为什么Any()在C#空对象上不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在null上调用Any()时对象,它将在C#中引发ArgumentNullException.如果对象为null,则肯定没有'any',并且它可能应该返回false.

When calling Any() on a null object, it throws an ArgumentNullException in C#. If the object is null, there definitely aren't 'any', and it should probably return false.

为什么C#会这样表现?

Why does C# behave this way?

推荐答案

在处理引用类型时,null值在语义上与空"值不同.

When dealing with reference types, a null value is semantically different from an "empty" value.

null字符串与string.Empty不同,并且null IEnumerable<T>Enumerable.Empty<T>(或该类型的任何其他空"枚举)不相同.

A null string is not the same as string.Empty, and a null IEnumerable<T> is not the same as Enumerable.Empty<T> (or any other "empty" enumerable of that type).

如果Any不是扩展方法,则在null上调用它会导致NullReferenceException.由于它是扩展方法,因此抛出一些异常(虽然不是必需的)是个好主意,因为它保留了尝试在null上调用方法的众所周知的语义: BOOM!

If Any were not an extension method, calling it on null would result in NullReferenceException. Since it is an extension method, throwing some exception (although not necessary) is a good idea because it preserves the well-known semantics of trying to call a method on null: BOOM!

这篇关于为什么Any()在C#空对象上不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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