我如何检查字符串数组中的null?

问题描述 投票:0回答:1

我正在开发我的第一个应用,该应用旨在作为待办事项应用。我对这一切有点新我希望这个问题不要太令人讨厌。我正在尝试构建一些代码来检查字符串数组是否为null。这是我的代码


int checkForNull(string[] a, int arrayNum)
    {
        for (int x = -1; x < arrayNum ; x ++ )
        {
            if (a[x].Length == 0)
                //^^ This is a problem for some reason
            {
                return (x);
            }
        }
        return (-1);
    }

我正在尝试解析一个数组并返回以null返回的第一个整数。这是我用来向应用程序添加新类别的一部分。我收到的错误出现在'if(a [x] .Length == 0)'“数组索引超出范围”。我也尝试过'if(a [x] == null)',但收到相同的错误。有什么想法吗?

谢谢。

c#
1个回答
0
投票

代码应为:

int checkForNull(string[] a)
{
    for (int x = 0; x < a.Length ; x++ )
    {
        if (string.IsNullOrEmpty(a)) // Covers both cases: null empty
            return x;
    }
    return -1;
}
© www.soinside.com 2019 - 2024. All rights reserved.