【问题标题】:Codedom generate complex if statementCodedom 生成复杂的 if 语句
【发布时间】:2015-06-03 00:55:21
【问题描述】:

我有点坚持尝试生成如下所示的复杂 if 语句

if (class1.Property == class2.Property || (class3.Property && class4.Property))
{
  //do something
}
else
{
   //do something else
}

通过使用 CodeConditionStatement 类,我可以生成上面的第一个条件,但我似乎找不到添加第二个条件的方法,尤其是使用所需的括号以及在运行时评估 if 的方式?

注意:我不想使用 CodeSnippetExpression 类。

有什么想法吗?

提前致谢。

【问题讨论】:

  • 内括号在发布的示例中是无用的,因为有或没有它们的结果是相同的(即使它被评估的顺序应该是相同的)!
  • ...虽然它确实有助于可视化表示条件的表达式树
  • 将代码示例的布尔逻辑改为需要括号

标签: c# code-generation codedom


【解决方案1】:

将条件分成3个二进制表达式:(class1.Property == class2.Property || (class3.Property || class4.Property)

  1. class3.Property || class4.Property - CodeBinaryOperatorExpression 左右两侧有 CodePropertyReferenceExpression
  2. class1.Property == class2.Property - CodeBinaryOperatorExpression,左侧和右侧带有 CodePropertyReferenceExpression
  3. 最后是#2 || #1 - CodeBinaryOperatorExpression #2 在左边,#1 在右边

【讨论】:

    【解决方案2】:

    首先,一种简单的方法是声明一个布尔变量。 将其初始化为 false 和 if 操作该变量的序列。 不要担心性能或可读性,有时它更具可读性。

    bool x = false;
    if (class1.Property == class2.Property)
    {
        x = true;
    }
    if (class3.Property == class4.Property)
    {
        x = true;
    }
    
    if (!anotherthingtocheck)
        x = false;
    
    if (x)
    {
        // Do something
    }
    else
    {
        // Do something else
    }
    

    【讨论】:

      【解决方案3】:

      简化为仅比较布尔值,但保留 if、else...

      CodeEntryPointMethod start = new CodeEntryPointMethod();
      //...
      start.Statements.Add(new CodeVariableDeclarationStatement(typeof(bool), "ifCheck", new CodePrimitiveExpression(false)));
      var e1 = new CodeBinaryOperatorExpression(new CodePrimitiveExpression(false), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(false));
      var e2 = new CodeBinaryOperatorExpression(new CodePrimitiveExpression(false), CodeBinaryOperatorType.IdentityEquality, new CodePrimitiveExpression(true));
      var ifAssign = new CodeAssignStatement(new CodeVariableReferenceExpression("ifCheck"), new CodeBinaryOperatorExpression(e1, CodeBinaryOperatorType.BooleanOr, e2));
      start.Statements.Add(ifAssign);
      var x1 = new CodeVariableDeclarationStatement(typeof(string), "x1", new CodePrimitiveExpression("Anything here..."));
      var ifCheck = new CodeConditionStatement(new CodeVariableReferenceExpression("ifCheck"), new CodeStatement[] { x1 }, new CodeStatement[] { x1 });
      start.Statements.Add(ifCheck);
      

      生成:

      bool ifCheck = false;
      ifCheck = ((false == false) 
          || (false == true));
      if (ifCheck) {
          string x1 = "Anything here...";
      }
      else {
          string x1 = "Anything here...";
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-09-06
        • 2017-05-28
        • 2016-04-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多