null 和空字符串数组的问题

问题描述 投票:0回答:1
class ToDoList { 
    public static void toDO() {

        List<string[]> addEntry = [];
        bool toDoLoop = true;

        while (toDoLoop) {
            Clear(); 
            WriteLine("\n\t\tHere is your to do list!");

            for (int i = 1; i < addEntry.Count; i++)
            {
                WriteLine($"\n\t\tTo Do {i}: {addEntry[i][0]}");
            }
            Write("\n\t\t[N]ew Entry\t[E]xit\t");

            string? userChoice = ReadLine();
            switch (userChoice)
            {
                case "n":
                case "N":
                    Write("\n\t\tAdd New Entry: ");
                    string?[] newToDo = new string[1];

                    newToDo[0] = ReadLine();

                    if (newToDo.Length == 0) { 
                        WriteLine("\n\t\tEntries can't be null!"); 
                    }

                    else { 
                        addEntry.Add(newToDo); 
                    }
                    break;

                case "e":
                case "E":
                    Clear();
                    WriteLine("\n\n\t\tClosing To Do!");
                    toDoLoop = false;
                    break;

                default:
                    Clear();
                    WriteLine("\n\t\tInvalid Entry!");
                    break;
            }
        }
    }
}

我尝试了不同的变体,在 if 和 else 中都添加了添加条目,但我没有让它工作。我的想法完全错误还是至少走在正确的道路上?

if (newToDo[0] == "")

if (newToDo[0] != )

if (newToDo[0] is null)

if (newToDo[0] is not null)

if (!string.IsNullOrEmpty(newToDo[0]))
c# arrays string arraylist null
1个回答
1
投票

数组始终具有“固定长度”。任何改变它的东西实际上都是一个新数组。所以当你有这行代码时: string?[] newToDo = new string[1];

我们可以知道,
newToDo.Length

永远
1,无论您是否曾经为任何项目设置过值,除非您为引用分配一个全新的数组。因此这个检查:
if (newToDo.Length == 0) { 

永远不会

成为true。我们已经知道我们将其设置为一个具有

.Length
属性为
1
的数组。
那么您应该使用哪种替代方案?根据我的经验,最后一个选项是最正确的:

if (!string.IsNullOrEmpty(newToDo[0]))

但有时这也很有用:

if (!string.IsNullOrWhiteSpace(newToDo[0]))

但是有人想知道为什么你有一个 
string[]

列表,而不是

string
列表(无数组),后者会简单得多,而且似乎仍然可以满足你的需求。

当我在这里时,C# 中的索引器 (
[]

) 属性从

0
 开始,而不是 
1
,因此这段代码值得怀疑:
for (int i = 1; i < addEntry.Count; i++)

您可能想要更多类似这样的东西:

for (int i = 0; i < addEntry.Count; i++) { WriteLine($"\n\t\tTo Do {i++}: {addEntry[i][0]}"); }

然后在读取要使用的行号的输入时也进行相应的 
-1

调整。

    

© www.soinside.com 2019 - 2024. All rights reserved.