基础概念
运算符重载使用了一个名为operator的关键字, 重载运算符后,在使用时会调用重载后的方法,使用这种方法可以实现对象之间自定义+-操作。
可重载运算符:
一元运算符:+, -, !, ~, ++, --
算术运算符:+, -, *, /, %
比较运算符:==, !=, <, >, <=, >=
代码示例
此段代码重载了+,==,!=,
public class Student
{
private int level;
private string name;
private int description;
public Student(int level, string name, int description)
{
this.level = level;
this.name = name;
this.description = description;
}
public static Student operator +(Student stu1, Student stu2)
{
Student stu = new Student(0,"", 0);
stu.level = stu1.level + stu2.level;
stu.name = stu1.name + stu2.name;
stu.description = stu1.description + stu2.description;
return stu;
}
public static bool operator ==(Student stu1, Student stu2)
{
if (stu1.name == stu2.name)
{
return true;
}
return false;
}
public static bool operator !=(Student stu1, Student stu2)
{
if (stu1.level != stu2.level)
{
return true;
}
return false;
}
public override string ToString()
{
Debug.Log(this.level);
Debug.Log(this.name);
Debug.Log(this.description);
return this.name;
}
}
表现
Student stu1 = new Student(4,"hzj", 100);
Student stu2 = new Student(6,"yzx", 200);
(stu1 + stu2).ToString();
if (stu1 == stu2)
{
Debug.Log("姓名相等");
}
else if (stu1 != stu2)
{
Debug.Log("年级不相等");
}
输出: