mpe*_*pen 4 c# visual-studio-2010
我有一行代码,
list[index++] = recursiveFunction();
Run Code Online (Sandbox Code Playgroud)
难道index之前或通话后得到递增recursiveFunction?
在函数调用之前执行递增操作.请参阅http://msdn.microsoft.com/en-us/library/aa691322(v=VS.71).aspx.请注意,这与运算符的优先级和关联性无关.
表达式中运算符的求值顺序由运算符的优先级和关联性决定(第7.2.1节).
表达式中的操作数从左到右进行计算.例如,在
F(i) + G(i++) * H(i)方法F中使用旧值i调用,然后用旧值i调用方法G,最后,用新值i调用方法H. 这与运算符优先级分开并且与运算符优先级无关.
运算符优先级和关联性仅影响运算符绑定到操作数的方式.这里的问题讨论了操作数评估的副作用.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
打印:
Increment operator is executed.
Function call.
Assignment called with original indexer value.
Run Code Online (Sandbox Code Playgroud)
此行为在规范中明确指定,并且在任何符合标准的编译器中应该相同.
在Windows上的Visual Studio 2008/.NET Framework 3.5下,索引在 recursiveFunction调用之前会递增.此示例应用程序将"index = 1"打印到控制台.
class Program
{
private int index = 0;
private static void Main()
{
new Program().TryMe();
}
private void TryMe()
{
var list = new List<int>();
list.Add(1);
list.Add(2);
list[index++] = ReturnZero();
}
private int ReturnZero()
{
Console.WriteLine(string.Format("index = {0}", index));
return 0;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2750 次 |
| 最近记录: |