Unity C# 运算符重载

使用 operator 关键字来声明运算符。 运算符声明必须符合以下规则:

1.同时包含 public 和 static 修饰符。

2.一元运算符采用一个参数。 二元运算符采用两个参数。 在每种情况下,都至少有一个参数必须具有类型 T 或 T?,其中 T 是包含运算符声明的类型。

using System;

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
    }
}

可以通过定义从 int 到 Fraction 的隐式转换来扩展前面的示例。 然后,重载运算符将支持这两种类型的参数。 也就是说,可以将一个整数添加到一个分数中,得到一个分数结果。

还可以使用 operator 关键字来定义自定义类型转换。 

 

可重载运算符

下表提供了 C# 运算符可重载性的相关信息:

运算符可重载性
+x-x!x~x++--truefalse这些一元运算符可以进行重载。

x + yx - yx * yx / yx % yx & yx | yx ^ yx << y

x >> yx == yx != yx < yx > yx <= yx >= y

这些二元运算符可以进行重载。 某些运算符必须成对重载;有关详细信息,请查看此表后面的备注。
x && yx || y无法重载条件逻辑运算符。 但是,如果具有已重载的 true 和 false 运算符的类型还以某种方式重载了 & 或 | 运算符,则可针对此类型的操作数分别计算 && 或 || 运算符。 有关详细信息,请参阅 C# 语言规范用户定义条件逻辑运算符部分。
a[i]元素访问不被视为可重载运算符,但你可定义索引器
(T)x强制转换运算符不能重载,但可以定义新的转换运算符。 有关详细信息,请参阅用户定义转换运算符
+=-=*=/=%=&=|=^=<<=>>=复合赋值运算符不能显式重载。 但在重载二元运算符时,也会隐式重载相应的复合赋值运算符(若有)。 例如,使用 +(可以进行重载)计算 +=

^xx = yx.yc ? t : fx ?? yx ??= yx..yx->y=>

f(x)asawaitcheckeduncheckeddefaultdelegate

isnameofnewsizeofstackalloctypeof

这些运算符无法进行重载。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值