调用实例方法委托时“this”不能为null错误排查
解决"Delegate to an instance method cannot have null 'this'"错误
问题描述
我尝试运行这段代码来筛选集合:
var result = filteredResults.Where(row => applicantSearchRequestModel.Subjects.Where(s => s != null).All(row.SubjectArea.Contains)).ToList();
其中:
filteredResults是一个List,每个元素带有SubjectArea字符串属性applicantSearchRequestModel.Subjects是字符串数组
需求是:筛选出SubjectArea包含数组中所有非空元素的项,但运行时抛出错误:
委托指向的实例方法不能拥有null的'this'。
错误原因
直接把row.SubjectArea.Contains作为参数传给All()方法时,存在两个问题:
- 如果
row.SubjectArea为null,调用实例方法Contains就会触发空引用错误,也就是报错里提到的"null 'this'" - 这种隐式传递实例方法的写法,编译器无法正确绑定委托逻辑,容易引发歧义
修复后的代码
var result = filteredResults.Where(row => applicantSearchRequestModel.Subjects .Where(s => s != null) .All(subject => row.SubjectArea != null && row.SubjectArea.Contains(subject)) ).ToList();
逻辑说明
- 先过滤掉
Subjects数组中的null元素,避免无效检查 - 显式遍历每个非空
subject,先判断row.SubjectArea是否为null(提前规避空引用),再检查是否包含当前subject - 只有当所有非空
subject都被SubjectArea包含时,当前元素才会被保留到结果集中
内容的提问来源于stack exchange,提问作者Paritosh
相关产品推荐
相关产品推荐

