C#中的增量和后增量 [英] Preincrement and postincrement in C#

查看:179
本文介绍了C#中的增量和后增量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  int a = 10;
int c = a++ + a++ + ++a;
MessageBox.Show(a.ToString());
MessageBox.Show(c.ToString());







  int a = 10;
int c = a++ + a++ - ++a;
MessageBox.Show(a.ToString());
MessageBox.Show(c.ToString());





我尝试过:



大家好,

创建以上预增量增量和后增量后,

两种代码都有所不同按照C ++概念解决方案。

请为C#提供正确的概念。



What I have tried:

Hi All,
After creating Above Program Of Pre Increment And Post Increment,
Both Code Have Different Solution As Per C++ Concept.
Please Give The Proper Concept For C#.

推荐答案

简单的答案是:将这些增量运算符用作单个只有语句,永远不要将它们与其他语句组合!这根本不会减慢程序的速度,编译器无论如何都必须创建额外的变量。你用这种组合造成的唯一一件事是:混乱。
The simple answer is: use those increment operators as single statements only, never combine them with other statements! That won't slow down your program at all, the compiler will have to create the extra variables anyway. The only thing you cause with such combinations is: confusion.


不要这样做。

看看这个答案:表达式如何工作c = ++ a + ++ a; [ ^ ]


您处于灰色区域。在C / C ++ / C#定义中,声明允许编译器更改表达式中元素的顺序(以及更多),并且由于表达式取决于操作的顺序,因此结果是不可预测的。另一个编译器将给出不同的结果。



使用调试器并显示生成的汇编代码,以查看代码的翻译方式。
You are in gray zone. In C/C++/C# definitions, it is stated that the compiler is allowed to change the order of elements in an expression (and more), and since your expression depend on the order of operations, the result is not predictable. Another compiler will give different results.

Use a debugger and display assembly code generated to see how your code was translated.


这篇关于C#中的增量和后增量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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