C#检查引用前是否存在对象

问题描述:

我想知道是否有办法在引用之前检查对象是否存在。不只是检查它是否为空,因为这也不起作用。我使用EPPlus软件包来读取excel文件,当它到达一个没有任何数值的索引时,它会发送一个异常。C#检查引用前是否存在对象

private DataTable WorksheetToDataTable(string tableName) 
{ 
    excelSheet = excelWorkbook.Worksheets[tableName]; 
    DataTable dt = new DataTable(); 
    try 
    { 
     int totalRows = excelSheet.Dimension.End.Row; 
     int totalCols = excelSheet.Dimension.End.Column; 
     for (int j = 1; j <= totalCols; j++) 
     { 

      dt.Columns.Add(); 
      for (int i = 1; i <= totalRows; i++) 
      { 
       if (j == 1) 
       { 
        dt.Rows.Add(); 
       } 
       try 
       { 
        dt.Rows[i - 1][j - 1] = excelSheet.Cells[i, j].Value.ToString(); 
        //dt.Rows[i - 1][j - 1] = Object.ReferenceEquals(null, excelSheet.Cells[i, j].Value.ToString()) ? "" : excelSheet.Cells[i, j].Value.ToString(); 
       } 
       catch 
       { 
        dt.Rows[i - 1][j - 1] = ""; 
       } 
      } 
     } 
     return dt; 
    } 
    catch 
    { 
     MessageBox.Show("Error: Referenced Excel Table is empty, or indexed improperly! Check Excel formatting.", "Error"); 
     return dt; 
    } 
} 

所以你可以看到我已经试过检查是否excelSheet.Cells[i, j].Value.ToString()是以前空,并将其发送夹在try/catch语句我有上述相同的异常。我要解析很多细胞和他们中的很多将是完全空的,它增加了扔了很多

例外的:在BBSApp.exe

“System.NullReferenceException”到输出安慰。有没有办法检查对象是否存在,然后我调用对象甚至检查它是否为null而没有try/catch?

if(excelSheet.Cells[i, j].Value.ToString() != null) 

简单地检查它是否如上所示为空发送相同的异常,因为它不存在在第一位。

+8

“简单地检查它是否为空,如上所示,因为它不首先存在发送相同的异常”不,那是检查调用ToString()*的结果是否为null。你应该检查'excelScheet'是否为空(看起来不太可能),或者如果'excelSheet.Cells [i,j]'为空或者'excelSheet.Cells [i,j] .Value'为null。 –

试试这个:

if(excelSheet.Cells[i, j].Value != null) 

你正在检查看Value属性为null。发生空引用异常是因为您正在尝试调用null对象上的方法ToString()

或者,您可以使用空接入运营商:

if(excelSheet.Cells[i, j]?.Value?.ToString() != null) 
+3

“?? null”是多余的,因为它基本上说“如果左侧为空,则使用右侧也是空的”。 – ckuri

+1

哎呀 - 是的。 – Michael

访问excelSheet场之前,您可以检查对象是否已被初始化使用空支票传播:

if (excelSheet.Cells[i, j]?.Value != null) 
    // Do whatever 

根据the documentation,您应该使用IsEmpty

如果指定的Range对象为空,则返回值Empty(使用IsEmpty函数来测试这种情况)。如果Range对象包含多个单元格,则返回一个值数组(使用IsArray函数来测试这种情况)。

实施例:

if (!excelSheet.Cells[i, j].Value.IsEmpty) 
{ 
    dt.Rows[i - 1][j - 1] = excelSheet.Cells[i, j].Value.ToString(); 
}