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

C#使用IComparable接口比较对象时出现NullReferenceException报错问题

问题原因

你遇到的空引用错误有三类可能的触发点:

  • CompareTo方法传入的other参数为null(符合IComparable接口的传入约定)
  • 当前Booker实例的ClientData属性为null
  • 被比较的other实例的ClientData属性为null
修复方案

首先修改CompareTo方法,添加全链路空值校验,同时符合C# IComparable的排序约定(null值默认排在非null值之前):

public int CompareTo(Booker other)
{
    // 处理other为null的情况:非null对象默认排在null之后
    if (other == null) return 1;

    // 处理两个实例的ClientData空值情况
    if (this.ClientData == null && other.ClientData == null) return 0;
    if (this.ClientData == null) return -1;
    if (other.ClientData == null) return 1;

    // 两者ClientData都非空,正常比较NumDay
    return this.ClientData.NumDay.CompareTo(other.ClientData.NumDay);
}
额外注意事项
  • 以上是兼容空值的通用修复方案,如果你业务逻辑不允许ClientData为null,需要在Booker类的构造函数中强制初始化ClientData属性,从根源避免空值产生。
  • 你代码中new List<Booker>(8)只是指定列表的初始容量为8,不会自动生成8个Booker元素,你需要手动调用Add方法向列表中添加实例,添加前请确保每个实例的ClientData已经完成初始化。

内容的提问来源于stack exchange,提问作者user17166166

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:57:02