转换运算符
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;