c# - C# 中如何比较两个对象的值

标签 c#

我创建了一个结构

 public struct MyCalender : IComparable<MyCalender>
{
 public int CompareTo(PersianDate other)
    {
        return DateTime.Compare(this, other);
    }
 .
 .
 .
 .
 .
}

我在另一个用户控件中新建了两个对象,我想比较它们。

我使用此代码,但出现错误。

 MyCalender value = new MyCalender(2010,11,12);
 MyCalender value2 = new MyCalender(2010,11,12);
        if (value < value2) ==> geterror

最佳答案

IComparable暴露 CompareTo <>必须单独重载:

class Foo : IComparable<Foo>
{
    private static readonly Foo Min = new Foo(Int32.MinValue);

    private readonly int value;

    public Foo(int value)
    {
        this.value = value;
    }

    public int CompareTo(Foo other)
    {
        return this.value.CompareTo((other ?? Min).value);
    }

    public static bool operator <(Foo a, Foo b)
    {
        return (a ?? Min).CompareTo(b) < 0;
    }

    public static bool operator >(Foo a, Foo b)
    {
        return (a ?? Min).CompareTo(b) > 0;
    }
}

编辑了代码,以便与 null 进行比较时不会失败。 。为了简单起见,我使用了一个快捷方式,除非 valueInt32.MinValue为一个适当的Foo 。严格来说,您必须检查 null显式获取 the contract右:

By definition, any object compares greater than (or follows) null, and two null references compare equal to each other.

此外,实现 IComparable<T>意味着CompareTo(T value)接受参数 T 。因此MyCalendar : IComparable<MyCalender>应该实现一个方法 CompareTo(MyCalendar other)而不是PersianDate (或实现 IComparable<PersianDate> )。

关于c# - C# 中如何比较两个对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12916332/

相关文章:

c# - 有没有更好的方法将 JObject 转换为接口(interface)的任何实现?

c# - 显式基类型转换时可能冗余操作码

c# - 关于缓存的线程安全 IEnumerable<T> 实现的性能

c# - 如何在具有可变字段的 .NET 应用程序中包含 HTML 文档?

c# - 如果已存在,则从元组列表中删除项目,忽略顺序 c#

c# - 如何解析存储为 char(16) 的 Uuid?

c# - SQL Server 中的 varbinary 类型如何在 C# 中的函数中使用

c# - 自动修剪位图到最小尺寸?

c# - 如何在程序运行时创建列表

c# - 物理数据类型