C#中如何重载运算符?

重载运算符的基本语法

在C#中,重载运算符需要通过operator关键字定义静态方法,方法名即为要重载的运算符符号。例如,重载+运算符的语法如下:

public static ReturnType operator +(Type1 a, Type2 b)
{
    // 实现逻辑
}

支持重载的运算符类型

C#允许重载以下两类运算符:

  1. 一元运算符:如+-!~++--truefalse
  2. 二元运算符:如+-*/%&|^<<>>==!=<><=>=

重载一元运算符的示例

以下代码展示了如何重载+-一元运算符:

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public static Point operator +(Point p)
    {
        return p; // 一元+通常直接返回原对象
    }

    public static Point operator -(Point p)
    {
        return new Point { X = -p.X, Y = -p.Y };
    }
}

重载二元运算符的示例

以下代码展示了如何重载+二元运算符:

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public static Point operator +(Point a, Point b)
    {
        return new Point { X = a.X + b.X, Y = a.Y + b.Y };
    }
}

重载比较运算符的注意事项

重载比较运算符(如==!=)时,必须成对重载,且逻辑需一致。通常还需要重写EqualsGetHashCode方法:

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public static bool operator ==(Point a, Point b)
    {
        return a.X == b.X && a.Y == b.Y;
    }

    public static bool operator !=(Point a, Point b)
    {
        return !(a == b);
    }

    public override bool Equals(object obj)
    {
        if (obj is Point p)
            return this == p;
        return false;
    }

    public override int GetHashCode()
    {
        return X.GetHashCode() ^ Y.GetHashCode();
    }
}

不支持重载的运算符

以下运算符不能重载:

  • 条件运算符(如&&||),但可通过重载&|间接实现。
  • 赋值运算符(如=+=),但重载+会自动支持+=
  • 索引运算符(如[]),但可通过索引器实现类似功能。
  • 类型转换运算符(如(int)),但可通过定义显式/隐式转换实现。

隐式与显式类型转换的重载

可以通过implicitexplicit关键字重载类型转换:

public class Point
{
    public int X { get; set; }
    public int Y { get; set; }

    public static implicit operator string(Point p)
    {
        return $"({p.X}, {p.Y})";
    }

    public static explicit operator Point(string s)
    {
        var parts = s.Split(',');
        return new Point { X = int.Parse(parts[0]), Y = int.Parse(parts[1]) };
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值