[英]Will c# compiler optimize empty if blocks
Is there a chance that C# will optimize the following code block? C#是否有可能优化以下代码块?
if (specField == null || AddSystemType(specField, layout)
|| AddEnumType(specField, layout)
|| AddUserType(specField, layout))
{
}
Well you can use ildasm to see what the compiler has optimized for yourself. 好了,您可以使用ildasm来查看编译器为您自己进行了优化。 But if you were expecting it to remove the code entirely, it can't - because those three method calls could throw exceptions or modify state.
但是,如果您期望它完全删除代码,则不能-因为这三个方法调用可能会引发异常或修改状态。 So the best it could do would be to emit the equivalent of:
因此,最好的办法是发出以下内容:
if (specField != null)
{
if (!AddSystemType(specField, layout))
{
if (!AddEnumType(specField, layout))
{
AddUserType(specField, layout);
}
}
}
The AddSystemType will execute and could change some states, so everything in the IF will be executed. AddSystemType将执行并可能更改某些状态,因此IF中的所有内容都将执行。
When using AND 使用AND时
if(specField == null && AddSystemType()) {
}
Then if specField is (always) null, AddSystemType() isn't executed and skipped (short circuit evaluation) 然后,如果specField为(总是)为null,则不会执行和跳过AddSystemType()(短路评估)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.