【问题标题】:I am not able to compare two objects using IComparable interface in C# [duplicate]我无法在 C# 中使用 IComparable 接口比较两个对象 [重复]
【发布时间】:2021-10-16 07:11:20
【问题描述】:

这是我的代码,我是编程新手:我从早上开始就在尝试,但找不到解决方案,请更正我的代码并帮助我。谢谢。

other.ClientData.NumDay <== getting null here.

我收到此错误:

System.NullReferenceException: '对象引用未设置为对象的实例。'

assignment3.Booker.ClientData.get 返回 null。

public int CompareTo(Booker other)
{
        if (this.ClientData.NumDay > other.ClientData.NumDay)
        {
            return 1;
        }
        else if (this.ClientData.NumDay < other.ClientData.NumDay)
        {
            return -1;
        }
        else
        {
            return 0;
        }
}


List<Booker> appointment = new List<Booker>(8)

foreach (var val in appointment)
{
    Console.WriteLine(val);
}
appointment.Sort();

foreach (var val in appointment)
{
    Console.WriteLine(val);
}

【问题讨论】:

    标签: c# .net icomparable


    【解决方案1】:

    请在此处查看其他内容的实际情况。

    public int CompareTo(Booker other)
    {
        console.log(other, other.ClientData)
    }
    

    可能有ClientData 拼写不同或其他没有ClientData 或其他也可以为空。请检查并纠正

    另外,您可以保留支票

    public int CompareTo(Booker other)
    {
        if(other && other.ClientData)
        {
            if (this.ClientData.NumDay > other.ClientData.NumDay)
            {
                return 1;
            }else if (this.ClientData.NumDay < other.ClientData.NumDay)
            {
                return -1;
            }
            else
            {
                return 0;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-05
      • 2013-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      • 2013-04-10
      相关资源
      最近更新 更多