溫馨提示×

C#重載運(yùn)算符的實(shí)際應(yīng)用案例分享

c#
小樊
84
2024-08-21 13:04:28
欄目: 編程語言

  1. 向量相加:可以通過重載加號運(yùn)算符來實(shí)現(xiàn)向量的相加操作。
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. 自定義數(shù)據(jù)類型相加:可以通過重載加號運(yùn)算符來實(shí)現(xiàn)自定義數(shù)據(jù)類型的相加操作。
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
    }
}

這些例子展示了如何通過重載運(yùn)算符來實(shí)現(xiàn)自定義數(shù)據(jù)類型的特定操作,使代碼更加簡潔和易于理解。

0