65.9K
CodeProject 正在变化。 阅读更多。
Home

C# 5.0 参数列表评估中的破坏性变更

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.86/5 (13投票s)

2012 年 7 月 25 日

CPOL
viewsIcon

37642

在 C# 4.0 中,C# 编译器在参数列表中参数的评估顺序上存在一个错误。

C# 语言规范 在 §7.5.1.2 中指出“(…) 参数列表中的表达式或变量引用按顺序从左到右进行评估 (…)”。free hit counters

因此,当使用 C# 4.0 编译器编译这段代码

static void M(
    int x = 10,
    int y = 20,
    int z = 30)
{
    Console.WriteLine(
        "x={0}, y={1}, z={2}", x, y, z);
}

static void Main(string[] args)
{
    int a = 0;

    M(++a, z: ++a);
}

并运行,会得到这个意外的输出

x=2, y=20, z=1

事实上,修复这个编译器缺陷是 C# 5.0 中引入的少数几个破坏性变更之一。

使用 5.0 编译器,可以得到预期的结果

x=1, y=20, z=2

为了避免这种类型的意外情况,应避免在参数列表中进行表达式评估。

使用这段代码

int a = 0;

int i = ++a;
int j = ++a;

M(i, z: j);

C# 4.0 和 C# 5.0 都能得到相同的结果

x=1, y=20, z=2
© . All rights reserved.