开发者

Codedom generate complex if statement

I'm a bit stuck with try to generate a complex if statement like the one below

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

By using the CodeConditionStatement class I can generate the first condition above but I can not seem to find a way 开发者_开发百科to add the second condition especially with the needed brackets and the way if will be evaluated at runtime?

Note: I do not want to use the CodeSnippetExpression class.

Any ideas?

Thanks in advance.


Separate the condition into 3 binary expressions: (class1.Property == class2.Property || (class3.Property || class4.Property)

  1. class3.Property || class4.Property - CodeBinaryOperatorExpression with CodePropertyReferenceExpression on left and right
  2. class1.Property == class2.Property - CodeBinaryOperatorExpression with CodePropertyReferenceExpression on left and right
  3. Finally #2 || #1 - CodeBinaryOperatorExpression #2 on left and #1 on right


First, a simple way would be to declare a boolean variable. Initialize it to false and to the sequence of if manipulating that variable. Don't worry about performance or readibility, sometime it is more readable.

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
}


Simplified to just compare booleans, but retaining the 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);

generates:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜