首页 > C#中运算符重载问题

C#中运算符重载问题

先上代码,这段代码是我找网上的“运算符重载”相关的资料,自己写的。刚刚学习C#,请见谅。
// ">"重载
public static bool operator >(Robot r1, Robot r2)
        {
            int max;
            int min;
            if (r1.Age > r2.Age)
            {
                max = r1.Age;
                min = r2.Age;
                return true;
            }
            else
            {
                max = r2.Age;
                min = r1.Age;
                return false;
            }
        }
        // "<"重载
        public static bool operator <(Robot r1, Robot r2)
        {
            int max;
            int min;
            if (r1.Age < r2.Age)
            {
                max = r2.Age;
                min = r1.Age;
                return true;
            }
            else
            {
                max = r1.Age;
                min = r2.Age;
                return false;
            }
        }

我想知道的是:
1.这段代码有什么不合理的地方么?
2.运算符的重载,返回值类型只能是Boolean类型的吗?


我想这个例子可以说明你的问题

csusing System;

namespace ConsoleApplication2
{
    class Robot
    {
        public int Age { get; set; }

        public static int operator >(Robot o1, Robot o2)
        {
            return o1.Age + o2.Age;
        }

        public static int operator <(Robot o1, Robot o2)
        {
            return o1.Age - o2.Age;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Robot r1 = new Robot
            {
                Age = 10
            };

            Robot r2 = new Robot
            {
                Age = 15
            };

            Console.WriteLine(r1 > r2);
            Console.WriteLine(r1 < r2);
        }
    }
}

要说你的代码有啥问题……最大的问题是 maxmin 完全没得用,你完全可以这样定义

cspublic static bool operator >(Robot r1, Robot r2) {
    return r1.Age > r2.Age;
}
public static bool operator <(Robot r1, Robot r2) {
    return r1.Age < r2.Age;
}

另外还有一个问题就是没有考虑参与比较的 Robot 对象为 null 的情况

【热门文章】
【热门文章】