适用范围:C# 7.0及以上版本
C#学习-运算符重载(operator) - 百度文库 (baidu.com)
官网文档:Operator overloading - C# reference | Microsoft Docs
public readonly struct Fraction { private readonly int num; private readonly int den; public Fraction(int numerator, int denominator) { if (denominator == 0) { throw new ArgumentException("Denominator cannot be zero.", nameof(denominator)); } num = numerator; den = denominator; } public static Fraction operator +(Fraction a) => a; public static Fraction operator -(Fraction a) => new Fraction(-a.num, a.den); public static Fraction operator +(Fraction a, Fraction b) => new Fraction(a.num * b.den + b.num * a.den, a.den * b.den); public static Fraction operator -(Fraction a, Fraction b) => a + (-b); public static Fraction operator *(Fraction a, Fraction b) => new Fraction(a.num * b.num, a.den * b.den); public static Fraction operator /(Fraction a, Fraction b) { if (b.num == 0) { throw new DivideByZeroException(); } return new Fraction(a.num * b.den, a.den * b.num); } public override string ToString() => $"{num} / {den}"; } public static class OperatorOverloading { public static void Main() { var a = new Fraction(5, 4); var b = new Fraction(1, 2); Console.WriteLine(-a); // output: -5 / 4 Console.WriteLine(a + b); // output: 14 / 8 Console.WriteLine(a - b); // output: 6 / 8 Console.WriteLine(a * b); // output: 5 / 8 Console.WriteLine(a / b); // output: 10 / 4 } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?