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
    }
}
相关推荐
格林威1 小时前
C# 相机Burst模式图像采集:使用相机内存配合OpenCvSharp和Halcon实现短时间的高速采集的方法
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·工业相机
J总裁的小芒果2 小时前
参数过多-分批传参
c#
典典分享指南2 小时前
短视频分镜提示词:让 AI 出片的产品口播
java·c#·bash·composer·symfony
Z5998178413 小时前
c#软件开发学习笔记--WPF(Canvas、数据绑定、MVVM模式、值转换器)
笔记·学习·c#
淡海水5 小时前
05-03-栈队列-PriorityQueue-TElement-TPriority-NET6优先队列语义与四叉堆实现
服务器·前端·c#·priorityqueue·clr·telement
leonkay18 小时前
C# 特性(Attribute)——【1】基础讲解
开发语言·青少年编程·面试·c#·.net·个人开发
CSDN_RTKLIB18 小时前
数据库七大符号表
c#
leonkay19 小时前
C# 特性(Attribute)——【2】工业设备参数框架设计
经验分享·面试·架构·c#·学习方法·设计
2501_9065651220 小时前
小创 · 智能助手
开发语言·c#
datalover1 天前
【无标题】
c#·linq