c# - int++ 什么时候递增?

标签 c# visual-studio-2010

我有一行代码,

list[index++] = recursiveFunction();

index 是在调用 recursiveFunction 之前还是之后递增?

最佳答案

增量操作在函数调用之前执行。参见 http://msdn.microsoft.com/en-us/library/aa691322(v=VS.71).aspx .请注意,这与运算符的优先级和结合性无关。

The order of evaluation of operators in an expression is determined by the precedence and associativity of the operators (Section 7.2.1).

Operands in an expression are evaluated from left to right. For example, in F(i) + G(i++) * H(i), method F is called using the old value of i, then method G is called with the old value of i, and, finally, method H is called with the new value of i. This is separate from and unrelated to operator precedence.

运算符优先级和结合性只影响运算符绑定(bind)到操作数的方式。这里的问题讨论的是操作数求值的副作用

using System;

class Obj {
   public bool Incremented {get;set;}
   public static Obj operator ++ (Obj o) {
     Console.WriteLine("Increment operator is executed.");
     return new Obj {Incremented = true};
   }
}

class L {
  public int this[Obj o] {
    set { Console.WriteLine("Assignment called with " + 
            (o.Incremented ? "incremented" : "original") + " indexer value."); }
  }

}
class Test{
  static void Main() {
    Obj o = new Obj();
    L l = new L();
    l[o++] = Func();
  }

  static int Func() {
    Console.WriteLine("Function call.");
    return 10;
  }
}

打印:

Increment operator is executed.
Function call.
Assignment called with original indexer value.

此行为在规范中明确规定并且在任何符合标准的编译器中都应该相同。

关于c# - int++ 什么时候递增?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4310229/

相关文章:

c# - 我可以将 using 语句与 RHV(右手值)一起使用吗?

c# - Entity Framework 是否可用于 Visual Studio 2008 Express Edition?

c# - ASP.NET MVC : Requested registry access denied when creating performance counters

C# ToolStrip 是透明的但边框仍然可见?

asp.net-mvc - Visual Studio 2010 : MVC project : filename or extension is too long.(hresult 异常:0x800700ce)

visual-studio-2010 - Visual Studio 可执行文件运行两次

c++ - 使用类模板的问题

c# - ServiceStack 在 IReturn<T> 中使用接口(interface)作为模板

javascript - 是否可以在 Visual Studio 中突出显示某些代码行?

c++ - 为 Visual Studio 2010 设置 OpenCV-2.3