我创建了一个结构
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
进行比较时不会失败。 。为了简单起见,我使用了一个快捷方式,除非 value
是 Int32.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/