C#,当数组可能没有元素时,如何判断数组的第一个元素是否为空?

标签 c#

这段代码会抛出一个空指针异常。

if (myArray[0] != null)
{
    //Do Something
}

如何测试以确保存在元素@index 0? 数组为空时不抛出异常。

最佳答案

根据您需要检查的内容,这些条件的一些组合:

if (myArray != null && myArray.Length > 0 && myArray[0] != null)
{
    //Do Something
}

关于C#,当数组可能没有元素时,如何判断数组的第一个元素是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10523481/

相关文章:

c# - NHibernate分层递归查询

c# - 如何在 MVC 中发布项目列表

c# - 洗牌列表 <Button> 失去与 mainpage.xaml 的连接

c# - Windows 窗体 : detect the change of the focused control

c# - 记录服务 SOAP 请求和响应

c# - Dotnet 十六进制字符串到 Java

c# - 检查 ListBox 中的重复项

C# 实用功能静态方法/静态类/单例模式

c# - Entity Framework 抛出错误 "Unable to evaluate the expression. Operation not supported. Unknown error: 0x80070057."

c# - 高效删除多条记录