运算符重载

基础概念

运算符重载使用了一个名为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("年级不相等");
        }

输出:

posted @   请明月  阅读(21)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示