由于类型之间不能用+拼接 解决办法:运算符重载
特点:
1.运算符重载的声明方式:operator 关键字
2.必须用public修饰且必须是类的静态的方法
3.重载运算符的方法 不用主动调用 只要使用重载的运算符就相当调用了方法
4.运算符只能采用值参数,不能采用ref或out参数
5.重载运算符的返回值不一定必须是自己,但一定不能是void
internal class Program
{
static void Main(string[] args)
{
People p = people1 + people2;
Console.WriteLine(p.Age);
Console.WriteLine(p.Name);
Console.WriteLine(p.Height);
People p1 = people1 - people2;
Console.WriteLine(p1.Age);
Console.WriteLine(p1.Name);
Console.WriteLine(p1.Height);
bool isSuccess = !people1;
// people1 += people2; 不能显式重载 因为重载了+后 系统会自动重载 +=
Console.ReadKey();
}
public class People{
public int Age { set; get; }
public int Height { set; get; }
public string Name { set; get; }
// 对于+的重载
//对于+ 运算符的重载
public static People operator +(People stu1, People stu2)
{
People tempPeople = new People();
tempPeople.Age = stu1.Age + stu2.Age;
tempPeople.Height= stu1.Height + stu2.Height;
tempPeople.Name = stu1.Name + stu2.Name;
return tempPeople;
}
//对于+ 运算符的重载
public static People operator -(People stu1, People stu2)
{
People tempPeople = new People();
tempPeople.Age = stu1.Age - stu2.Age;
tempPeople.Height = stu1.Height - stu2.Height;
tempPeople.Name = "aaaa";
return tempPeople;
}
//对于! 运算符的重载
public static bool operator !(People stu1)
{
if (stu1.Age >18) {
Console.WriteLine("你成年了!但是不能吸烟");
return !true;
}
else
{
Console.WriteLine("你未成年了!但是能去赚钱");
return !false;
}
}
}
}
运算符 可重载性
! ++、--、 可以重载这些一元运算符
+、-、*、/、%、&、| 可以重载这些二元运算符
==、!=、<、>、<=、>= 可以重载比较运算符,必须成对重载
&&、|| 不能重载条件逻辑运算符,但可以使用能够重载的&和|进行计算
+=、-=、*=、/=、%=、&=、|=、^=、<<=、>>= 不能显式重载赋值运算符,
在重写单个运算符如+、-、%时,它们会被 隐式重写
=、.、?:、->、new、is、sizeof、typeof () [] 不能重载这些运算符