优播图库,9887地铁笨蛋6,电讯一代
使用
operator
关键字重载内置运算符,或在类或结构声明中提供用户定义的转换。
假设场景,一个student类,有语文和数学两科成绩,chinese math,加减两科成绩,不重载运算,代码如下。
class student { /// <summary> /// 语文成绩 /// </summary> public double chinese { get; set; } /// <summary> /// 数学成绩 /// </summary> public double math { get; set; } }
比较两个成绩差距
var a = new student { chinese = 90.5d, math = 88.5d }; var b = new student { chinese = 70.5d, math = 68.5d }; //a的语文比b的语文高多少分 console.writeline(a.chinese - b.chinese); //a的数学比b的数学高多少分 console.writeline(a.math - b.math);
使用operator
重载 -
class student { /// <summary> /// 语文成绩 /// </summary> public double chinese { get; set; } /// <summary> /// 数学成绩 /// </summary> public double math { get; set; } public static student operator -(student a, student b) { return new student { chinese = a.chinese - b.chinese, math = a.math - b.math }; } }
比较成绩差距的代码可以改为
class program { static void main(string[] args) { var a = new student { chinese = 90.5d, math = 88.5d }; var b = new student { chinese = 70.5d, math = 68.5d }; var c = a - b; //a的语文比b的语文高多少分 console.writeline(c.chinese); //a的数学比b的数学高多少分 console.writeline(c.math); } }
参考:运算符(c# 参考)
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Blazor server side 自家的一些开源的, 实用型项目的进度之 CEF客户端
.NET IoC模式依赖反转(DIP)、控制反转(Ioc)、依赖注入(DI)
vue+.netcore可支持业务代码扩展的开发框架 VOL.Vue 2.0版本发布
网友评论