简体   繁体   中英

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. 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. 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.

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. In some other cases they might have been really needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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