gpt4 book ai didi

c# - 检查数组是否为 null 或空?

转载 作者:太空狗 更新时间:2023-10-29 17:30:39 27 4
gpt4 key购买 nike

我对这行代码有一些问题:

if(String.IsNullOrEmpty(m_nameList[index]))

我做错了什么?

编辑:m_nameList 在 VisualStudio 中带有红色下划线,并显示“名称‘m_nameList’在当前上下文中不存在”??

编辑 2:我添加了更多代码

    class SeatManager
{
// Fields
private readonly int m_totNumOfSeats;

// Constructor
public SeatManager(int maxNumOfSeats)
{
m_totNumOfSeats = maxNumOfSeats;

// Create arrays for name and price
string[] m_nameList = new string[m_totNumOfSeats];
double[] m_priceList = new double[m_totNumOfSeats];
}

public int GetNumReserved()
{
int totalAmountReserved = 0;

for (int index = 0; index <= m_totNumOfSeats; index++)
{
if (String.IsNullOrEmpty(m_nameList[index]))
{
totalAmountReserved++;
}
}
return totalAmountReserved;
}
}
}

最佳答案

如果 m_nameList 为空,它仍然会爆炸,因为它会尝试找到要传递给 String.IsNullOrEmpty 的元素。你会想要:

if (m_nameList == null || String.IsNullOrEmpty(m_nameList[index]))

如果 m_nameList 不为空,那也是假设 index 将有效。

当然,这是检查数组的元素 是否为null 或为空,或者数组引用本身是否为null。如果您只是想检查数组本身(如您的标题所示),您需要:

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

编辑:现在我们可以看到您的代码,有两个问题:

  • 正如 Henk 在他的回答中所展示的,当您需要一个字段时,您正在尝试使用一个本地变量
  • 会因为以下原因得到一个ArrayIndexOutOfBoundsException(一旦您使用了一个字段):

    for (int index = 0; index <= m_totNumOfSeats; index++)

    由于您的绑定(bind),这将执行 m_totNumOfSeats + 1 次迭代。你想要:

    for (int index = 0; index < m_totNumOfSeats; index++)

    请注意 m_nameList[m_totNumOfSeats] 无效,因为数组索引在 C# 中从 0 开始。因此,对于包含 5 个元素的数组,有效索引为 0、1、2、3、4。

GetNumReserved 方法的另一个选项是使用:

int count = 0;
foreach (string name in m_nameList)
{
if (string.IsNullOrEmpty(name))
{
count++;
}
}
return count;

或者使用 LINQ,这是一个单行代码:

return m_nameList.Count(string.IsNullOrEmpty);

(你确定你没有弄错吗?我原以为保留是名称​​不为空或空的,而不是它 null 或空的。)

如果是错误的方式,在 LINQ 中将是这样的:

return m_nameList.Count(name => !string.IsNullOrEmpty(name));

关于c# - 检查数组是否为 null 或空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10052914/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com