简体   繁体   English

关于此内联分配的c#规则是什么

[英]what is the c# rule about this inline assignment

I was expecting the result to be 0 我期望结果为0

dotnetfiddler demo dotnetfiddler演示

using System;

public class Program
{
    public static void Main()
    {
        int value = 5;
        value += (value += 5) > 5 ? -value : +value;

        Console.WriteLine(value);
    }
}
  1. value start at 5 值从5开始
  2. value increase to 10 价值增加到10
  3. the coalesce detect that it is higher than 5 合并检测到它高于5
  4. it return -10 它返回-10

since value was detected to be higher than 5, which mean it had the value of 10 in this case, i was expecting 10 += -10 由于检测到的值大于5,这意味着在这种情况下其值为10,因此我期望10 + = -10

what is happening is 5 += -10 发生了什么事5 + = -10

what define this behavior? 什么定义了这种行为?

I believe it functions like so: 我相信它的功能如下:

int value = 5;
value += //5 is stored here for the calculation
   (value += 5) // 5 is modified to 10
     > 5 
     ? -value //-10 
     : +value; //10

so you get 5 - 10 = -5 所以你得到5 - 10 = -5

Further reading: MSDN 进一步阅读: MSDN

Lets look at the emitted IL in Release Mode: 让我们看一下释放模式下发出的IL:

Program.Main:
IL_0000:  ldc.i4.5    // Load 5
IL_0001:  stloc.0     // Store value
IL_0002:  ldloc.0     // Load value
IL_0003:  dup         // Create a duplicate of value (5)
IL_0004:  ldc.i4.5    // Load 5
IL_0005:  add         // Add 5 to variable. Now value == 10
IL_0006:  dup         // Duplicate value.
IL_0007:  stloc.0     // Store value (10)
IL_0008:  ldc.i4.5    // Load 5
IL_0009:  bgt.s       IL_000E // Check value (10) > 5. If true go to IL_000E
IL_000B:  ldloc.0     // value
IL_000C:  br.s        IL_0010
IL_000E:  ldloc.0     // Load value (10)
IL_000F:  neg         // Negate value (-10)
IL_0010:  add         // -10 + 5 = -5
IL_0011:  stloc.0     // Store -5 in value
IL_0012:  ldloc.0     // value
IL_0013:  call        System.Console.WriteLine // Print value
IL_0018:  ret  

This kind of code is confusing. 这种代码令人困惑。 Try avoiding it at all costs. 尝试不惜一切代价避免它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM