在.NET BODMAS原则 [英] BODMAS principle in .NET

查看:208
本文介绍了在.NET BODMAS原则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我发现,在.NET框架遵循操作BODMAS为了做计算的时候。即计算以下列顺序进行:

I discovered today that the .NET framework follows the BODMAS order of operations when doing a calculation. That is calculations are carried out in the following order:

  • 在括号
  • 订单
  • 添加

不过,我已搜索周围,找不到任何文档确认.NET的绝对的遵循这一原则,有没有这样的文档哪儿了吗?我会很感激,如果你可以点我在正确的方向。

However I've searched around and can't find any documentation confirming that .NET definitely follows this principle, are there such docs anywhere? I'd be grateful if you could point me in the right direction.

推荐答案

注意,C#不这样做BODMAS规则你在学校学到的方法。假设你有:

Note that C# does not do the BODMAS rule the way you learned in school. Suppose you have:

A().x = B() + C() * D();

您可能会天真地认为乘法是做第一,然后添加和分配最后,因此,这是等价的:

You might naively think that multiplication is "done first", then the addition, and the assignment last, and therefore, this is the equivalent of:

c = C();
d = D();
product = c * d;
b = B();
sum = b + product;
a = A();
a.x = sum;

但是,这不会发生什么变化。 的BODMAS规则只要求操作的在正确的顺序进行;中的的操作数的,可以计算任意顺序排列。

But that is not what happens. The BODMAS rule only requires that the operations be done in the right order; the operands can be computed in any order.

在C#中,操作数计算的左到右。所以在这种情况下,会发生什么是逻辑上是相同的:

In C#, operands are computed left-to-right. So in this case, what would happen is logically the same as:

a = A();
b = B();
c = C();
d = D();
product = c * d;
sum = b + product;
a.x = sum;

此外,C#不这样做的每次的乘法的每次的除了前。例如:

Also, C# does not do every multiplication before every addition. For example:

A().x = B() + C() + D() * E();

时,计算为:

a = A();
b = B();
c = C();
sum1 = b + c;
d = D();
e = E();
product = d * e;
sum2 = sum1 + product;
a.x = sum2;

看,乘法之前最左边除了发生;乘法只有前发生了的最右边的的补充。

基本上,规则是正确圆括号前pression让你只有二元运算符,然后在右侧前每个二进制运算符左侧的评价。因此,我们的例子是:

Basically, the rule is "parenthesize the expression correctly so that you have only binary operators, and then evaluate the left side of every binary operator before the right side." So our example would be:

A().x = ( ( B() + C() ) + ( D() * E() ) );

和现在很清楚。最左边除了是一个操作数最右边增加,因此,最左边除了必须在乘法之前执行,因为左操作数右操作数之前一直执行。

and now it is clear. The leftmost addition is an operand to the rightmost addition, and therefore the leftmost addition must execute before the multiplication, because the left operand always executes before the right operand.

如果你这个问题的兴趣,在它上面看到我的文章:

If this subject interests you, see my articles on it:

<一个href="http://blogs.msdn.com/b/ericlippert/archive/tags/$p$pcedence/">http://blogs.msdn.com/b/ericlippert/archive/tags/$p$pcedence/

这篇关于在.NET BODMAS原则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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