C# 自定义类重载运算符

转换运算符

public class Bool
{
    public bool value;
	// 把Bool强制转换为bool
    public static explicit operator bool(Bool v)
    {
        return v.value;
    }    
    // 把bool隐式转换为Bool
    public static implicit operator Bool(bool v)
    {
        return new Bool(v);
    }
}

Bool a = true;
bool b = (bool)a;

比较运算符

注意使用哈希相关的容器时需要重写HashCode

public class GameTime
{
    public int Day, Hour, Minute;
    public static bool operator <(GameTime a, GameTime b)
    {
        if (a.Day != b.Day) return a.Day < b.Day;
        if (a.Hour != b.Hour) return a.Hour < b.Hour;
        return a.Minute < b.Minute;
    }
    public static bool operator >(GameTime a, GameTime b)
    {
        return b < a;
    }
    public static bool operator ==(GameTime a, GameTime b)
    {
        return !(a < b) && !(b < a);
    }
    public static bool operator !=(GameTime a, GameTime b)
    {
        return a < b || b < a;
    }
    public static bool operator >=(GameTime a, GameTime b)
    {
        return !(a < b);
    }
    public static bool operator <=(GameTime a, GameTime b)
    {
        return !(b < a);
    }
}

GameTime a, b;
if(a > b || a <= b){
	
}

重载加号

隐藏问题:操作符重载, 二元运算符的参数之一必须是包含类型
问题原因:没有把重载的实现,写在操作符左或右边的类型中

    public static GameTime operator +(GameTime a, int minute)
    {
        GameTime res = new GameTime(a.Day, a.Hour, a.Minute);
        res.Minute += minute;
        if (res.Minute >= 60)
        {
            res.Hour += res.Minute / 60;
            res.Minute %= 60;
        }
        if (res.Hour >= 24)
        {
            res.Day += res.Hour / 24;
            res.Hour %= 24;
        }
        return res;
    }

GameTime a, b;
a = b + 120;

posted @ 2021-08-19 11:03  yassine  阅读(222)  评论(0编辑  收藏  举报