C#-运算符重载

关键词:operator

语法:
cs 复制代码
public static void operator 运算符(参数列表){}

作用:让自定义类或结构体对象,可以使用运算符进行运算

注意:

  1. 参数的数量:与所重载的运算符的运算规则有关。如加法只能有2个参数

  2. 条件运算符需要配对实现:一旦重载了==,就必须重载!=

  3. 一个符号可以多个重载

  4. 不能用ref和out

特点:

  1. 一定是一个公共的静态方法

  2. 返回值写在operator前

  3. 逻辑处理自定义

不可重载的运算符

逻辑与(&&) 逻辑或(||)

索引符 \[\]

强转运算符 ()

特殊运算符

点. 三目运算符? : 赋值符号=

参数的类型:必须有一个参数跟返回值的参数一样

示例
cs 复制代码
class Student
{
    private int age;  private string name;
    public Student (int age,string name)
    {
        this.age=age;  this.name=name;
    }
    //重载
    public static bool operator == (Student s1,Student s2)
    {
        if(s1.age==s2.age && s1.name==s2.name)
          return true;
        else
          return false;
    }
    
    //重载   //一旦重载了==,就必须重载!=
    public static bool operator != (Student s1,Student s2)
    {
        bool result s1==s2;  //调用了上面的重载运算符
        return !result;
    }
    //调用
    Main()
    {
        Student s1=new Student(17,"张三");
        Student s2=new Student(17,"张三");
        Console.WriteLine(s1==s2);
        //重载前:返回false,∵比较的是在栈中存储的内存地址
        //重载后:返回true
    }
}
相关推荐
aini_lovee22 分钟前
C# 快递单打印系统(万能套打系统)
开发语言·c#
白菜上路26 分钟前
C# Serilog.AspNetCore基本使用
c#·serilog
小白不白1111 小时前
C# WinForm 与 VP 二次开发
开发语言·c#
SunnyDays10112 小时前
如何使用 C# 自动调整 Excel 行高和列宽
开发语言·c#·excel
itgather3 小时前
OfficeExcel — Word / Excel DLL 验证台功能介绍
c#·word·excel
云中小生3 小时前
Scrutor:.NET 依赖注入自动化的优雅实现
c#·.net
郝亚军3 小时前
Visual Studio 2022项目中的.sln是什么?
c++·c#·visual studio
jghhh013 小时前
C# 图片水印工具(支持9个位置)
数据库·microsoft·c#
咸鱼翻身小阿橙4 小时前
C# WinForms 控件学习项目
开发语言·学习·c#
JaydenAI4 小时前
[MAF预定义Agent中间件-03]FunctionInvocationDelegatingAgent:将AOP引入函数调用
ai·c#·agent·aop·maf