我创建了一个这样的数组
string[] directories = new string[15];
然后我想像这样用它做点什么
for (int i = 0; i < directories.Length; i++) {
//code
}
用户可以在数组中输入任意数量的目录,但如果他们不在其中放入 14 个元素,则数组的其余部分显然将为 NULL,for 循环直到它才会停止到达第14个元素。如何使循环停止在数组中的最后一个目录并且不计算 NULL?
我已经试过了,但它返回了以下错误:System.NullReferenceException: 'Object reference not set to an instance of an object.'
for (int i = 0; i < directories .Length; i++) {
//code
string directory = directories[i];
if (directory.Equals(null)){
return;
}
// more code
}
谢谢,抱歉缺乏经验和英语不好。
最佳答案
尝试:。
directories.Count(x => x != null):
如果您始终可以保证在第一个 null 之后,其他所有内容都为 null,那么下面的代码将取代您代码中的 if 语句,并且比上面的 linq 更高效:
if (directory == null)
break;
break 关键字可防止在 c# 中出现更多循环。
如果您真的希望数组中有一组值后跟一组空值,您是否考虑过使用列表而不是数组?
关于c# - 如何计算数组的长度而不包括 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58951376/