C# 运算符重载

Posted 时空观察者9号

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C# 运算符重载相关的知识,希望对你有一定的参考价值。

C#运算符重载函数必须是public static

    struct CSTest
    {
        public int posx;
        public static CSTest operator + (CSTest o1, CSTest o2)
        {//二元运算符重载
            CSTest ost = new CSTest();
            ost.posx = o1.posx + o2.posx;
            return ost;
        }
        public static CSTest operator - (CSTest ot)
        {//一元运算符重载
            ot.posx = -ot.posx;
            return ot;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            CSTest ostn1 = new CSTest();
            CSTest ostn2 = new CSTest();
            ostn1.posx = 1;
            ostn2.posx = 2;
            CSTest ostn3 = ostn1 + ostn2;
            ostn3 = -ostn3;
            Console.WriteLine(ostn3.posx);
        }
    }

以上是关于C# 运算符重载的主要内容,如果未能解决你的问题,请参考以下文章