定义比较运算符如何应用于类型? [英] Define how a comparison operator is applied to a type?

查看:65
本文介绍了定义比较运算符如何应用于类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I define whether and how a comparison operator is applied to operands of my type?

推荐答案

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

To use all of the operators, try this:

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();
    }
}

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

A good tutorial on this: http://winsharp93.wordpress.com/2009/06/28/implementing-icomparablet-iequatablet-and-the-equality-members/

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

Since you know the interfaces IComparable, IEquatable needs to be implemented you can tell if two instances of yourClass are comparable by using this (example):

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

这篇关于定义比较运算符如何应用于类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆