运算符重载
基础概念
运算符重载使用了一个名为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("年级不相等");
}
输出:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)