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
    }
}
相关推荐
PfCoder13 小时前
C# 中的定时器 System.Threading.Timer用法
开发语言·c#
缺点内向13 小时前
Word 自动化处理:如何用 C# 让指定段落“隐身”?
开发语言·c#·自动化·word·.net
KvPiter13 小时前
Clawdbot 中文汉化版 接入微信、飞书
人工智能·c#
曹牧13 小时前
C#:重载窗体构造函数
开发语言·c#
mudtools14 小时前
飞书多应用开发:如何实现企业多应用的“系统集成引擎“
c#·.net·飞书
暮疯不疯1 天前
C#常见术语表格
开发语言·c#
JQLvopkk1 天前
VS2015使用C#连接KepserverEX并操作读写节点
开发语言·c#
流水线上的指令侠1 天前
补充说明——针对《C#:从 0 到 1 创建基于 NUnit + FlaUI 的 WPF UI 自动化测试项目》
功能测试·ui·c#·自动化·wpf
流水线上的指令侠1 天前
C# 实战:从 0 到 1 搭建基于 NUnit + FlaUI 的 WPF UI 自动化测试项目
功能测试·ui·c#·自动化·wpf·visual studio
gc_22991 天前
学习C#调用OpenXml操作word文档的基本用法(20:学习嵌入文件类)
c#·word·openxml·嵌入文档