遭遇“Cannot perform runtime binding on a null reference exception”异常求助
解决“无法对空引用执行运行时绑定”异常问题
我自认为理解“Cannot perform runtime binding on a null reference exception”(无法对空引用执行运行时绑定)异常的含义,也检查了相关代码,但还是找不到触发异常的原因。
抛出异常的代码行:
for (int a = 0; a < (ItemList[i].Count - BufferSize); a++)
相关定义
ItemList是一个动态类型的二维列表,定义代码如下:
List<dynamic> ItemList = new List<dynamic>(); int BufferSize = 35;
触发异常的完整代码块
后续有代码填充ItemList,执行以下代码时,标注行抛出异常:
for (var i = 0; i < ItemList.Count; i++) { if (ItemList[i] != null) { if (ItemList[i].Count > BufferSize) { // 此行抛出异常 for (int a = 0; a < (ItemList[i].Count - BufferSize); a++) { ItemList[i][a].Image = null; } } } }
异常原因分析
- 虽然你判断了
ItemList[i] != null,但ItemList[i]是dynamic类型,运行时它可能根本不是拥有Count属性的集合类型——比如填充ItemList时,某个元素被赋值成了非集合的类型(比如单个对象、字符串等),这类值没有Count属性,访问时就会触发运行时绑定异常。 - 极端情况是多线程场景:在你判断
ItemList[i].Count > BufferSize后,到执行内部for循环前,ItemList[i]被其他线程修改成了无Count属性的类型或null。
解决方案
- 检查填充逻辑:确保
ItemList的每个元素都是拥有Count属性的集合类型(比如List<dynamic>),而非任意动态值。 - 增加类型校验:在访问
Count前,先确认ItemList[i]是集合类型:
for (var i = 0; i < ItemList.Count; i++) { var subList = ItemList[i] as ICollection; if (subList != null && subList.Count > BufferSize) { for (int a = 0; a < (subList.Count - BufferSize); a++) { var item = (dynamic)subList[a]; if (item != null) { item.Image = null; } } } }
- 避免重复动态绑定:将
ItemList[i]赋值给局部变量,减少运行时绑定的不确定性:
for (var i = 0; i < ItemList.Count; i++) { var subItem = ItemList[i]; if (subItem == null) continue; int count; try { count = subItem.Count; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException) { // 当前元素无Count属性,跳过 continue; } if (count > BufferSize) { for (int a = 0; a < (count - BufferSize); a++) { var item = subItem[a]; if (item != null) { item.Image = null; } } } }
- 替换dynamic类型:如果能确定子列表和元素的具体类型,尽量不用
dynamic,编译时就能提前发现错误。
内容的提问来源于stack exchange,提问作者user2217057
相关产品推荐
相关产品推荐

