简体   繁体   English

CodeDom 生成的代码中的额外括号

[英]Extra parentheses in CodeDom-generated code

I'm using CodeDom to generate code to be compiled later, and I've noticed that certain constructs create extra sets of parentheses.我正在使用 CodeDom 生成稍后要编译的代码,并且我注意到某些构造会创建额外的括号集。 While I know they don't affect anything, they do look strange.虽然我知道它们不会影响任何东西,但它们看起来确实很奇怪。

A sample of code that does it is this:执行此操作的代码示例如下:

new CodeConditionStatement(
  new CodeBinaryOperatorExpression(
    new CodePropertyReferenceExpression(new CodePropertySetValueReferenceExpression(), 
      "Length"),
    CodeBinaryOperatorType.GreaterThan,
    new CodePrimitiveExpression(strLength)
  ),
  new CodeThrowExceptionStatement(
    new CodeObjectCreateExpression(typeof(ArgumentException), 
    new CodePrimitiveExpression("The string is too long"), 
    new CodePrimitiveExpression("value"))
  )
)

This generates the following snippet:这会生成以下代码段:

if ((value.Length > 50)) {
    throw new System.ArgumentException("The string is too long", "value");
}

Again, I know that the extra parentheses don't affect anything, but if I'm doing something wrong to do this, I'd like to know:)同样,我知道额外的括号不会影响任何事情,但如果我做错了什么,我想知道:)

Looks good to me.在我看来很好。 I've been getting the same resulting code for ages.多年来,我一直得到相同的结果代码。

If you're only interested in code gen for C#, you could spell out the condition with CodeSnippetExpression , avoiding the extra parentheses.如果您只对 C# 的代码生成感兴趣,您可以使用CodeSnippetExpression拼出条件,避免使用额外的括号。 Your way is more general.你的方法更通用。

Under the hood, IL does not do parentheses resolution (it's the compiler's job), so if parentheses might be needed, they will be included explicitly.在幕后,IL 不做括号解析(这是编译器的工作),所以如果可能需要括号,它们将被显式包含在内。

My guess would be that the authors of the CodeDom didn't feel the advantage of a bit cleaner code would weight out against using the precious CPU time required to detect the need for the parentheses.我的猜测是,CodeDom 的作者并不觉得更简洁的代码的优势会抵消使用检测括号需要所需的宝贵 CPU 时间。 In some other cases they might have been really needed.在其他一些情况下,它们可能确实是需要的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM