首页 > 解决方案 > 设置变量错误无法对空引用执行运行时绑定

问题描述

我正在运行以下 C# 代码:

Excel.Workbook s_workbook = sApp.Workbooks.Open(s_file);
Excel._Worksheet s_ws = s_workbook.Worksheets[1];
string strst = s_ws.Cells[17][1].Value.ToString();

但是strst在上面代码的最后一行中设置变量时出现此错误:

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException
  HResult=0x80131500
  Message=Cannot perform runtime binding on a null reference
  Source=<Cannot evaluate the exception source>
  StackTrace:
<Cannot evaluate the exception stack trace>

我试过这样做,string strst = s_ws.Cells[17][1].Value.Convert.ToString();但我得到了同样的错误。有什么建议吗?

标签: c#.net

解决方案


似乎ValueorCells[17][1]是空的,你可以尝试这样的事情:

string strst = s_ws.Cells[17][1]?.Value?.ToString();

它被称为空条件运算符

空条件运算符是短路的。也就是说,如果条件成员或元素访问操作链中的一个操作返回 null,则链的其余部分不会执行。


推荐阅读