C#运算符

示例

通过使用operator关键字public和andstatic修饰符,可以使大多数内置运算符(包括转换运算符)超载。

运算符有三种形式:一元运算符,二进制运算符和转换运算符。

一元和二元运算符至少需要一个与包含类型相同的参数,有些则需要互补的匹配运算符。

转换运算符必须与封闭类型进行转换。

public struct Vector32
{
    
    public Vector32(int x, int y)
    {
        X = x;
        Y = y;
    }
    
    public int X { get; }
    public int Y { get; }

    public static bool operator ==(Vector32 left, Vector32 right)
        =>left.X==right.X&&left.Y== right.Y;

    public static bool operator !=(Vector32 left, Vector32 right)
        => !(left == right);

    public static Vector32 operator +(Vector32 left, Vector32 right)
        => new Vector32(left.X + right.X,left.Y+ right.Y);

    public static Vector32 operator +(Vector32 left, int right)
        => new Vector32(left.X + right,left.Y+ right);

    public static Vector32 operator +(int left, Vector32 right)
        => right + left;

    public static Vector32 operator -(Vector32 left, Vector32 right)
        => new Vector32(left.X - right.X,left.Y- right.Y);

    public static Vector32 operator -(Vector32 left, int right)
        => new Vector32(left.X - right,left.Y- right);

    public static Vector32 operator -(int left, Vector32 right)
        => right - left;

    public static implicit operator Vector64(Vector32 vector)
        => new Vector64(vector.X, vector.Y);

    public override string ToString() => $"{{{X}, {Y}}}";

}

public struct Vector64
{

    public Vector64(long x, long y)
    {
        X = x;
        Y = y;
    }

    public long X { get; }
    public long Y { get; }

    public override string ToString() => $"{{{X}, {Y}}}";

}

var vector1 = new Vector32(15, 39);
var vector2 = new Vector32(87, 64);
        
Console.WriteLine(vector1 == vector2); // 假
Console.WriteLine(vector1 != vector2); // 真
Console.WriteLine(vector1 + vector2);  // {102,103}
Console.WriteLine(vector1 - vector2);  // {-72,-25}