定义比较运算符如何应用于类型?

osv*_*ein 0 c# icomparable comparison-operators

如何定义比较运算符是否以及如何应用于我的类型的操作数?

Mar*_*cus 5

您可以使用 CompareTo 方法实现IComparable 接口。

要使用所有运算符,请尝试以下操作:

public sealed class Foo : IEquatable<Foo>, IComparable<Foo>
{
    public static int Compare(Foo first, Foo second)
    {
        if (Object.ReferenceEquals(first, null))
            return (Object.ReferenceEquals(second, null) ? 0 : -1);

        return first.CompareTo(second);
    }
    public static bool operator==(Foo first, Foo second)
    {
        return Object.Equals(first, second);
    }
    public static bool operator!=(Foo first, Foo second)
    {
        return !Object.Equals(first, second);
    }
    public static bool operator<(Foo first, Foo second)
    {
        return Foo.Compare(first, second) < 0;
    }
    public static bool operator >(Foo first, Foo second)
    {
        return Foo.Compare(first, second) > 0;
    }
    public static bool operator <=(Foo first, Foo second)
    {
        return Foo.Compare(first, second) <= 0;
    }
    public static bool operator >=(Foo first, Foo second)
    {
        return Foo.Compare(first, second) >= 0;
    }

    private string bar;

    public string Bar
    {
        //getter and setter
    }

   public bool Equals(Foo other)
    {
        if (Object.ReferenceEquals(other, null))
            return false;
        if (Object.ReferenceEquals(other, this)) //Not mandatory
            return true;

        return String.Equals(this.foo, other.foo);
    }
    public int CompareTo(Foo other)
    {
        if (Object.ReferenceEquals(other, null))
            return 1;
        if (Object.ReferenceEquals(other, this)) //Not mandatory
            return 0;

        return String.Compare(this.bar, other.bar);
    }
    public override bool Equals(object obj)
    {
        return this.Equals(obj as Foo);
    }
    public override int GetHashCode()
    {
        return this.bar == null ? 0 : this.bar.GetHashCode();
    }
}
Run Code Online (Sandbox Code Playgroud)

一个很好的教程:http : //winsharp93.wordpress.com/2009/06/28/implementing-icomparablet-iequatablet-and-the-equality-members/

由于您知道接口 IComparable,IEquatable 需要实现,您可以通过使用以下(示例)来判断 yourClass 的两个实例是否具有可比性:

if (yourClass is IEquatable<T> && yourClass2 is IEquatable<T> && yourClass is IComparable<T> && yourClass2 is IComparable<T>) //T is the same type
{
yourClass <= yourClass2;
}
Run Code Online (Sandbox Code Playgroud)