c#学习笔记 操作符重载

关键字
operator

特点
1. 一定是一个public的静态方法
2. 逻辑处理自定义

作用
让自定义的类或结构体能够使用运算符

基本语法:public static 返回类型 operator 运算符(参数列表)
{
//do something
}

实例:

	class Point
    {
        public int x;
        public int y;
        public Point (int x, int y) { this.x = x; this.y = y; }
        public static Point operator + (Point p1, Point p2)
        {
            Point res = new Point (0, 0);
            res.x = p1.x + p2.x;
            res.y = p1.y + p2.y;
            return res;
        }
        public static Point operator + (Point p1, int value)
        {
            Point res = new Point (0, 0);
            res.x = p1.x + value;
            res.y = p1.y;
            return res;
        }
        public override string ToString ()
        {
            return string.Format ("({0},{1})", this.x, this.y);
        }
    }
    
    class Program
    {
        static void Main (string[] args)
        {
            Point p1 = new Point (3, 4);
            Point p2 = new Point (2, 2);
            Console.WriteLine (p1 + p2); //(5,6)
            Console.WriteLine (p1 + 1); //(4,4)
        }
    }

注意
1. 条件运算符需要成对实现
2. 参数列表中至少要有一个为自定义的类或结构体
3. 一个符号可以多个重载
4. 不能使用ref和out

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值