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
    }
}
相关推荐
SunnyDays10111 小时前
使用 C# 添加、修改和删除 Excel VBA 宏 (无需 Microsoft Office Interop)
c#·excel··vba
影寂ldy1 小时前
C# 多接口、同名冲突、显式实现、接口继承 完整笔记
java·笔记·c#
诸葛大钢铁1 小时前
如何降低Word文件的体积?压缩Word文件的三种方法
开发语言·c#
专注VB编程开发20年1 小时前
阿里通义灵码插件安装失败
开发语言·ide·c#·visual studio
影寂ldy2 小时前
C# 泛型方法
java·前端·c#
caimouse2 小时前
Godot 4.7 内嵌 C# 模块切换到 .NET 9.0 编译指南
c#·.net·godot
z落落11 小时前
C# 泛型方法(原理、类型推断、多泛型参数)+泛型效率(普通类型 VS Object装箱 VS 泛型)
开发语言·c#
rockey62712 小时前
基于AScript的SQL脚本语言发布啦!
sql·c#·.net·script·expression·动态脚本
z落落13 小时前
C# 四种特殊类:抽象类、密封类、静态类、部分类
开发语言·c#
王cb15 小时前
WinRT Server and Client c#
开发语言·c#