C#重载运算符的实际应用案例分享

avatar
作者
筋斗云
阅读量:0

  1. 向量相加:可以通过重载加号运算符来实现向量的相加操作。
public class Vector {     public int X { get; set; }     public int Y { get; set; }      public Vector(int x, int y)     {         X = x;         Y = y;     }      public static Vector operator +(Vector v1, Vector v2)     {         return new Vector(v1.X + v2.X, v1.Y + v2.Y);     } }  class Program {     static void Main()     {         Vector v1 = new Vector(1, 2);         Vector v2 = new Vector(3, 4);          Vector result = v1 + v2;          Console.WriteLine($"Result: ({result.X}, {result.Y})"); // Output: Result: (4, 6)     } } 
  1. 自定义数据类型相加:可以通过重载加号运算符来实现自定义数据类型的相加操作。
public class ComplexNumber {     public int Real { get; set; }     public int Imaginary { get; set; }      public ComplexNumber(int real, int imaginary)     {         Real = real;         Imaginary = imaginary;     }      public static ComplexNumber operator +(ComplexNumber c1, ComplexNumber c2)     {         return new ComplexNumber(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);     } }  class Program {     static void Main()     {         ComplexNumber c1 = new ComplexNumber(1, 2);         ComplexNumber c2 = new ComplexNumber(3, 4);          ComplexNumber result = c1 + c2;          Console.WriteLine($"Result: {result.Real} + {result.Imaginary}i"); // Output: Result: 4 + 6i     } } 

这些例子展示了如何通过重载运算符来实现自定义数据类型的特定操作,使代码更加简洁和易于理解。

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!