因为运算符本身只是一种针对系统预定义的数学类型(int 、float、double),如果我们自己自定义的类要实现加法运算,就要进行“运算符重载”
格式:
public static 类型 operator 方法名
1、什么是运算符重载?
C#的一些运算符可以被重载,使其能够作用于特定的类和结构体,此过程称为运算符重载
2、那些运算符可以被重载
一元运算符合除了赋值以外的二元运算符可以被重载
赋值运算符不能被直接重载,但是由于赋值操作是根据算数、逻辑或位移运算产生的结果得来,所以也就间接的得以重载了
3、何时需要进行运算符重载?
运算符重载应该仅用与操作数表示的是数字含义的时候,并且能恰当的表达运算符的意思的时候
例如:给一个Employee类型的对象e提升员工等级时,不应该用e++,而应用e.Promote
当有>运算符重载后,就要有与之对应的<运算符重载。
class Time
{
private int hour;
private int min;
public Time(int hour, int min)
{
this.hour = hour;
this.min = min;
}
/// <summary>
/// 获取总分钟数
/// </summary>
/// <param name="t"></param>
/// <returns></returns>
public int GetTotalMinutes()
{
return this.hour * 60 + this.min;
}
public static Time operator + (Time t1,Time t2)
{
Time result = new Time(0, 0);
result.hour = t1.hour + t2.hour + (t1.min + t2.min) / 60;
result.min = (t1.min + t2.min) % 60;
return result;
}
public static bool operator > (Time t1, Time t2)
{
if (t1.GetTotalMinutes() > t2.GetTotalMinutes())
return true;
else
return false;
}
public static bool operator <(Time t1, Time t2)
{
if (t1.GetTotalMinutes() < t2.GetTotalMinutes())
{
return true;
}
else
{
return false;
}
}
public static bool operator <=(Time t1, Time t2)
{
return !(t1 > t2);
}
public static bool operator >=(Time t1, Time t2)
{
return !(t1 < t2);
}
public override string ToString()
{
return string.Format("{0,2}:{1,2}", hour, min);
}
}
class Program
{
static void Main(string[] args)
{
#region 时间相加
//Time t1 = new Time(8, 50);
//Time t2 = new Time(1, 50);
//Time x;
//x = t1 + t2;
//Console.WriteLine(x);
#endregion
#region 判断大小
//if (t1 > t2)
//{
// Console.WriteLine(t1);
//}
//else
//{
// Console.WriteLine(t2);
//}
#endregion
Time t1=new Time(1,50);
Time t2=new Time(2,50);
Debug.Assert(!(t1 > t2));//断言:判断一句话为真
Debug.Assert(t1 < t2);
Debug.Assert(!(t1 >= t2));
Debug.Assert(t1 <= t2);
Console.ReadLine();
}
}