如何重载在C#后缀和前缀运算符 [英] how to overload postfix and prefix operator in c#

查看:240
本文介绍了如何重载在C#后缀和前缀运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们如何实现在C#中后缀和前缀运算符重载

How do we implement the overload for postfix and prefix operators in c#

void Main()
{
    MyClass myclass=new MyClass();
    myclass.x=5;
    Console.WriteLine((++myclass).x);
          Console.WriteLine((myclass++).x);
}

public class MyClass
{
    public int x;
    public static MyClass operator ++(MyClass m)
    {
        m.x=m.x+1;
        return m;
    }

}

这可能是不必要的运算符重载,但它知道,++运算符可以被重载。我们如何在这里实现了不同的行为(我+ +,++ I)

this might be an unnecessary operator overload, but its known that ++ operator can be overloaded. How do we achieve the different behaviour here ( i++, ++i)

推荐答案

从我所看到的,重载一元。符++在C#中重载这两个运营商的后缀和前缀版本

From what I've seen, overloading the unary operator ++ in C# overloads both the postfix and prefix versions of the operator.

来源:
http://devhawk.net/2003/07/09/operator-overloading-in-c/
http://www.programmingvideotutorials.com/csharp/csharp-operator-overloading

这篇关于如何重载在C#后缀和前缀运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆