Why is there no difference in ++foo and foo++ when the ++ operator is overloaded?
本问题已经有最佳答案,请猛点这里访问。
Possible Duplicate:
Post-increment Operator Overloading
Why are Postfix ++/— categorized as primary Operators in C#?
我看到我可以超载
1 2 3 4 5 | int b = 2; //if i write this Console.WriteLine(++b); //it outputs 3 //or if i write this Console.WriteLine(b++); //outpusts 2 |
但是当涉及到运算符重载时,情况有点不同:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | class Fly { private string Status { get; set; } public Fly() { Status ="landed"; } public override string ToString() { return"This fly is" + Status; } public static Fly operator ++(Fly fly) { fly.Status ="flying"; return fly; } } static void Main(string[] args) { Fly foo = new Fly(); Console.WriteLine(foo++); //outputs flying and should be landed //why do these 2 output the same? Console.WriteLine(++foo); //outputs flying } |
我的问题是,为什么最后两行输出相同的内容?更具体地说,为什么第一行(两行)输出
解决方案是将操作员过载改为:
1 2 3 4 5 |
前缀与后缀