数组[1]不显示为空

本文关键字:显示 数组 | 更新日期: 2023-09-27 18:19:14

我在获取inputArray[1]的值作为我的if语句的空值时遇到了麻烦。

下面是代码:

static void GetInput()
    {
       string input = Console.ReadLine();
       string[] inputArray = input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        switch (inputArray[0])
        {
            case "exit":
                System.Console.WriteLine(inputArray[0]);
                Console.WriteLine("Exiting...");
                break;
            case "help":
                System.Console.WriteLine(inputArray[0]);
                Help();
                GetInput();
                break;
            case "openall":
                if (inputArray[1] != null) ;
                {
                    System.Console.WriteLine(inputArray[0] + " " + inputArray[1]);
                    fileExt = inputArray[1];
                    OpenFiles();
                    GetInput();
                }
                break;                         
        }
    }

现在我已经尝试了很多方法除了if (inputArray[1] != null);但是似乎什么都不起作用,所以我知道我的编程知识中有一些东西是我现在缺失的。

我得到这个错误:

索引超出了数组的边界。

感谢所有的帮助!

数组[1]不显示为空

在检查数组是否为空之前,需要测试数组的长度。

那么改变这个

if (inputArray[1] != null)

变成

if (inputArray.Length > 1 && inputArray[1] != null)

c#数组长度

正如在注释中提到的,更正确的代码应该是测试
if (inputArray.Length > 1)

as inputArray[1] != null永远不会为真。

if(inputArray.length > 1)代替if (inputArray[1] != null)

我只想在你的代码中添加一件事。

如果inputArray包含两个以上或相等的元素,则总是出现inputArray[1] != null条件。因为如果你分割数组,它不会返回'null',而且你已经指定了RemoveEmptyEntries,所以只需检查前面的答案中提到的长度。不需要检查null或empty。

我检查了一下你的代码,如果你输入的是类似"open xxx"的东西,那么它会正常工作,你写的两个单词之间必须有一个空格,因为你使用

   input.Spli(new char{' '} ) 
但是,

最好在尝试获取任何数组元素之前检查数组长度。

 if (inputArray.Length > [Array element index that you want to obtain ] ) 
            { 
                //TO DO 
            } 
            else 
            { 
                // TO DO
            } 

请记住,你的输入字符串必须包含许多独立的单词,这些单词用空格分隔,否则如果你的输入字符串不包含许多独立的单词,那么你的输入数组将只有一个元素