c#运算符重载

运算符重载 概念

让自定义类和结构体 能够使用运算符

使用关键字 operator

特点

一定是一个公共的静态方法 返回值写在operator前 逻辑处理自定义

条件运算符需要成对实现

一个符号可以多个重载

不能使用ref和out

语法

public static 返回类型 operator 运算符 (参数列表)

为+进行运算符重载,让Point类的类型对象进行相加

cs 复制代码
 class Point
 {
     public int x;
     public int y;
     public static Point operator +(Point p1,Point p2)
     {
         Point p = new Point();
         p.x = p1.x + p2.x;
         p.y = p1.y + p2.y; 
         return p;
     }
     public static Point operator +(Point p1, int value)
     {
         Point p = new Point();
         p.x = p1.x + value;
         p.y = p1.y + value;
         return p;
     }
 }

对重载使用时,只能按重载的参数顺序进行运算

例如:Point p4 = p + 2;//可以重载

Point p4 = 2 + p3;//没有对应的重载 ,参数顺序也要一致

cs 复制代码
 Point p = new Point();
 p.x = 1;
 p.y = 1;
 Point p2 = new Point();
 p2.x = 1;
 p2.y = 1;
 Point p3 = p + p2;//如果不进行重载 是不能相加的
 Point p4 = p + 2;//重载
 //Point p4 = 2 + p3;//没有对应的重载 ,参数顺序也要一致 
相关推荐
唐青枫10 小时前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫1 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6251 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902112 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠2 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫4 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech5 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf6 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6256 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech7 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf