鉴于这是一个非常自然的用例(如果你不知道as实际上是什么),
if (x is Bar) {
Bar y = x as Bar;
something();
}
Run Code Online (Sandbox Code Playgroud)
实际上是等效的(也就是说,编译器生成的CIL来自上面的代码将是等价的):
Bar y = x as Bar;
if (y != null) {
y = x as Bar; //The conversion is done twice!
something();
}
Run Code Online (Sandbox Code Playgroud)
编辑:
我想我没有说清楚我的问题.我不会写第二个片段,因为它当然是多余的.我声称在编译第一个片段时编译器生成的CIL等同于第二个片段,这是多余的.问题:a)这是正确的吗?b)如果是这样,为什么这样is实施?
这是因为我发现第一个片段比实际写得更好更清晰,更漂亮
Bar y = x as Bar;
if (y != null) {
something();
}
Run Code Online (Sandbox Code Playgroud)
结论:
优化is/ ascase不是编译器的责任,而是JIT的责任.
此外,与空检查它具有比这两个方案(较少(更便宜)的说明is和as和is和cast).
附录:
与nullcheck一样的CIL(.NET 3.5):
L_0001: ldarg.1 …Run Code Online (Sandbox Code Playgroud)