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
    }
}
相关推荐
颜x小1 小时前
[C#]泛型类与泛型方法
开发语言·c++·c#
caishenzhibiao1 小时前
顺势交易矩阵主图 同花顺期货通指标
java·c语言·c#
TDengine (老段)2 小时前
TDengine Node.js 与 C# 连接器 — Web 服务与 .NET 集成
大数据·数据库·node.js·c#·.net·时序数据库·tdengine
河西石头3 小时前
再谈C#的抽象类和接口:从“适配器”到“毛坯房”的设计哲学
开发语言·c#·接口·依赖注入·抽象类·依赖倒挂
颜x小3 小时前
[C#]——接口与继承
开发语言·c++·c#
颜x小17 小时前
[C#] C++与c#语法对比
开发语言·c++·c#
weixin_4236521318 小时前
C#使用JObject
开发语言·c#
Z59981784119 小时前
c#软件开发学习笔记--Modbus-RTU通讯
笔记·学习·c#
用户298698530141 天前
在 PC 上将 HTML 转换为 PDF 的3种有效方法
人工智能·c#·html
Rotion_深1 天前
C# 设计TCP Server
开发语言·tcp/ip·c#