简体   繁体   English

如果(数组.长度 == 0)

[英]If (Array.Length == 0)

If an array is empty, it looks like you can't check it's length using ".length".如果数组为空,则看起来您无法使用“.length”检查其长度。 What's the best way to check if an array is empty?检查数组是否为空的最佳方法是什么?

You can absolutely check an empty array's length.您绝对可以检查数组的长度。 However, if you try to do that on a null reference you'll get an exception.但是,如果您尝试对空引用执行此操作,则会出现异常。 I suspect that's what you're running into.我怀疑这就是你遇到的问题。 You can cope with both though:您可以同时应对两者:

if (array == null || array.Length == 0)

If that isn't the cause, please give a short but complete program demonstrating the problem.如果这不是原因,请提供一个简短但完整的程序来演示问题。 If that was the cause, it's worth taking a moment to make sure you understand null references vs "empty" collections/strings/whatever.如果这原因,那么值得花点时间确保您了解空引用与“空”集合/字符串/任何内容。

是的,为了安全起见,我可能会这样做:

if(array == null || array.Length == 0)

You can use您可以使用

if (array == null || array.Length == 0)

OR或者

if (!(array != null && array.Length != 0))

NOTE!!!!!笔记!!!!! To insure that c# will implement the short circuit correctly;确保 c# 将正确实现短路; you have to compare that the object with NULL before you go to the children compare of the object.您必须先将对象与 NULL 进行比较,然后再进行对象的子项比较。

C# 7.0 and above C# 7.0 及以上

if(!(array?.Length != 0))

如果长度为空且数组存在,您可以使用.Length == 0,但您确定它不为空吗?

As other have already suggested it is likely you are getting a NullReferenceException which can be avoided by first checking to see if the reference is null .正如其他人已经建议的那样,您很可能会收到NullReferenceException ,可以通过首先检查引用是否为null来避免该NullReferenceException However, you need to ask yourself whether that check is actually warranted.但是,您需要问问自己该检查是否真的有必要。 Would you be doing it because the reference really might be null and it being null has a special meaning in your code?您是否会这样做是因为引用确实可能为null并且它为null在您的代码中具有特殊含义? Or would you be doing it to cover up a bug?或者你会这样做来掩盖一个错误? The nature of the question leads me to believe it would be the latter.这个问题的性质使我相信它会是后者。 In which case you really need to examine the code in depth and figure out why that reference did not get initialized properly in the first place.在这种情况下,您确实需要深入检查代码并弄清楚为什么该引用没有被正确初始化。

Since .Net >= 5.0 the best way is to use Any :由于 .Net >= 5.0 最好的方法是使用Any

if(!array.Any()) {
   //now you sure it's empty
}

For nullable arrays:对于可为空数组:

if(!(array?.Any() == true)) {
   //now you sure it's null or empty
}

This is the best way.这是最好的方法。 Please note Array is an object in NET so you need to check for null before.请注意 Array 是 NET 中的对象,因此您需要先检查 null。

Jon Skeet answered correctly.乔恩斯基特回答正确。 Just remember that the order of the test in the "IF" is important.请记住,“IF”中的测试顺序很重要。 Check for the null before the length.在长度之前检查null I also prefer to put the null on the left side of the equal which is a habit I got from Java that made the code more efficient and fast… I don't think it's important in a lot of application today, but it's a good practice!我也更喜欢将null放在等号的左侧,这是我从 Java 中得到的一个习惯,它使代码更加高效和快速……我认为这在当今的许多应用程序中并不重要,但这是一个很好的做法!

if (null == array || array.Length == 0)

If array is null , trying to derefrence array.Length will throw a NullReferenceException .如果arraynull ,则尝试取消array.Length将抛出NullReferenceException If your code considers null to be an invalid value for array , you should reject it and blame the caller.如果您的代码认为nullarray的无效值,您应该拒绝它并归咎于调用者。 One such pattern is to throw ArgumentNullException :一种这样的模式是抛出ArgumentNullException

void MyMethod(string[] array)
{
    if (array == null) throw new ArgumentNullException(nameof(array));

    if (array.Length > 0)
    {
        // Do something with array…
    }
}

If you want to accept a null array as an indication to not do something or as an optional parameter, you may simply not access it if it is null:如果您想接受一个null数组作为不做某事的指示或作为可选参数,如果它为空,您可能根本无法访问它:

void MyMethod(string[] array)
{
    if (array != null)
    {
        // Do something with array here…
    }
}

If you want to avoid touching array when it is either null or has zero length, then you can check for both at the same time with C#-6's null coalescing operator .如果您想避免在arraynull或长度为零时接触array ,那么您可以使用C#-6 的 null 合并运算符同时检查两者。

void MyMethod(string[] array)
{
    if (array?.Length > 0)
    {
        // Do something with array…
    }
}

Superfluous Length Check多余的长度检查

It seems strange that you are treating the empty array as a special case.您将空数组视为特殊情况似乎很奇怪。 In many cases, if you, eg, would just loop over the array anyway, there's no need to treat the empty array as a special case.在许多情况下,例如,如果您无论如何只想遍历数组,则无需将空数组视为特殊情况。 foreach (var elem in array) {«body»} will simply never execute «body» when array.Length is 0 .array.Length0时, foreach (var elem in array) {«body»}将永远不会执行«body» If you are treating array == null || array.Length == 0如果您正在处理array == null || array.Length == 0 array == null || array.Length == 0 specially to, eg, improve performance, you might consider leaving a comment for posterity. array == null || array.Length == 0特别是为了提高性能,您可能会考虑为后代留下评论。 Otherwise, the check for Length == 0 appears superfluous.否则,检查Length == 0似乎是多余的。

Superfluous code makes understanding a program harder because people reading the code likely assume that each line is necessary to solve some problem or achieve correctness.多余的代码使理解程序变得更加困难,因为阅读代码的人可能会假设每一行都是解决某些问题或实现正确性所必需的。 If you include unnecessary code, the readers are going to spend forever trying to figure out why that line is or was necessary before deleting it ;-).如果您包含不必要的代码,读者将永远花时间在删除该行之前弄清楚为什么该行是必要的;-)。

Your suggested test is fine, so long as the array is intialised...您建议的测试很好,只要数组已初始化...

Martin.马丁。

check if the array is null first so you would avoid a null pointer exception首先检查数组是否为空,这样您就可以避免空指针异常

logic in any language: if array is null or is empty :do ....任何语言的逻辑:如果数组为空或为空:do ....

do you mean empty or null, two different things,你的意思是空的还是空的,两种不同的东西,

if the array is instantiated but empty, then length is correct, if it has not been instantiated then test vs null如果数组已实例化但为空,则长度正确,如果尚未实例化,则测试 vs null

// 还有另一种方法来检查数组是否包含项目

 if ( array.Count == 0) return;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM