√ C# - 05.怎么重载操作符(P305)

  1. 操作符的本质是对方法的简化。
  2. 实现操作符重载的方法必须是public static的,后面加上关键字operator和被重载的操作符,如【+】,且放在操作数的类中。
  3. 方法的返回值类型不能是void,但可以是其他类型。
using System;

namespace _05
{
    class Program
    {
        static void Main(string[] args)
        {
            Test1 test11 = new Test1(1);
            Test1 test12 = new Test1(2);

            Console.WriteLine("*****测试方法*****");
            Console.WriteLine($"test11 Add test12 = {Test1.Add(test11, test12).value}");
            Console.WriteLine();

            Console.WriteLine("*****测试操作符*****");
            Console.WriteLine($"test11  +  test12 = {(test11 + test12).value}");
            Console.WriteLine();
        }
    }

    class Test1
    {
        public int value;

        public Test1(int value)
        {
            this.value = value;
        }

        public static Test2 Add(Test1 test11, Test1 test12)
        {
            return new Test2(test11.value + test12.value);
        }

        public static Test2 operator +(Test1 test11, Test1 test12)
        {
            return new Test2(test11.value + test12.value);
        }
    }

    class Test2
    {
        public int value;

        public Test2(int value)
        {
            this.value = value;
        }
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值