You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用实例方法委托时“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()方法时,存在两个问题:

  1. 如果row.SubjectArea为null,调用实例方法Contains就会触发空引用错误,也就是报错里提到的"null 'this'"
  2. 这种隐式传递实例方法的写法,编译器无法正确绑定委托逻辑,容易引发歧义

修复后的代码

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 07:58:16