c# - 设置变量错误无法对空引用执行运行时绑定
问题描述
我正在运行以下 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();
但我得到了同样的错误。有什么建议吗?
解决方案
似乎Value
orCells[17][1]
是空的,你可以尝试这样的事情:
string strst = s_ws.Cells[17][1]?.Value?.ToString();
它被称为空条件运算符。
空条件运算符是短路的。也就是说,如果条件成员或元素访问操作链中的一个操作返回 null,则链的其余部分不会执行。
推荐阅读
- vue.js - 什么时候在 vue 中使用 created() 方法?
- android - Android Studio 未解决的参考。项目编译
- java - 如何使用 Jython 将 .pyc 文件反编译为 .py
- react-native - React Native Router Flux 中的安全区域实现
- c++ - 是否可以在 C++ 中声明另一个函数时使用函数返回类型作为参数?
- sap - SAP HANA 分区表计算视图与非分区表计算视图相比运行缓慢
- r - eval 中的错误(predvars、data、env):找不到对象“gdp”
- scala - 将过滤器作为参数传递给 Dataframe.filter 函数
- python - 没有 OOP 的 GUI 编程
- redis - 在 ioredis 上使用“zrevrange”和“scale reads: slaves”的问题