1.概要

1.1可重载运算符

1.2不可重载运算符

2.试验代码

using System;

namespace 运算符重载
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("运算符重载");
            Console.WriteLine("二元运算符:+");
            A a = new A();
            A b = new A();
            A c = a + b;
            Console.WriteLine(c.a);

            Console.WriteLine("一元运算符:++");
            A d = new A();
            d++;
            Console.WriteLine(d.a);


            Console.WriteLine("二元运算符:-");
            A e = new A();
            A f = new A();
            e = e - f;
            Console.WriteLine(e.a);

            Console.WriteLine("一元运算符:+x");
            A h = new A();
            Console.WriteLine((+h).a);
            Console.ReadKey();
        }
    }
    class A
    {
        public int a = 1;
        public static A operator +(A b, A c)
        {
            A a = new A();
            a.a = b.a + c.a;
            return a;
        }
        public static A operator ++(A b)
        {
            b.a++;
            return b;
        }
        public static A operator +(A b)
        {
            A a = new A();
            a.a = b.a + 1;
            return a;
        }
        public static A operator --(A b)
        {
            b.a--;
            return b;
        }
        public static A operator -(A b,A c)
        {
            A a = new A();
            a.a =  b.a-c.a;
            return b;
        }
        public static bool operator true(A x)
        {
            return x.a == 1;
        } 
        public static bool operator false(A x)
        {
            return x.a != 1;
        }
    }
}

 3.运行结果

c# 运算符重载-LMLPHP

 4.规律总结

1.有+x的重载,没有x+的重载。public static A operator +(A b) 的一元运算符都是符号再左侧。

05-03 19:52