[英]How to add forloop in If-Else condition in c#?[CODEDOM]
How to execute the following code in Codedom:如何在 Codedom 中执行以下代码:
if(statement)
{
for(int = 0; i < 10; i++)
{
Console.WriteLine(i);
}
}
I'm familiar with CodeIterationStatement and CodeConditionStatement but don't know how to execute it.我熟悉 CodeIterationStatement 和 CodeConditionStatement 但不知道如何执行。
What type of statement or condition you want to put to execute inside loop is depend upon requirement.您要在循环内执行什么类型的语句或条件取决于要求。 I guess there should be a condition inside if statement lets understand by example
我想if语句里面应该有一个条件让我们通过例子来理解
int a=5;
if(a>1)
{
for(int i=0;i<10;i++)
{
Console.WriteLine("{0}",i);
}
}
This should do the trick这应该可以解决问题
private CodeConditionStatement makeIfStatementWithLoop(CodeExpression conditionExpr, CodeExpression iterationLimit)
{
CodeConditionStatement ifStatement = new CodeConditionStatement();
ifStatement.Condition = conditionExpr;
CodeVariableDeclarationStatement iDeclaration = new CodeVariableDeclarationStatement(new CodeTypeReference(typeof(int)), "i");
CodeVariableReferenceExpression iReference = new CodeVariableReferenceExpression(iDeclaration.Name);
CodeIterationStatement loopStatement = new CodeIterationStatement();
loopStatement.InitStatement = new CodeAssignStatement(iReference, new CodePrimitiveExpression(0));
CodeAssignStatement incrementStatement = new CodeAssignStatement();
incrementStatement.Left = iReference;
incrementStatement.Right = new CodeBinaryOperatorExpression(iReference, CodeBinaryOperatorType.Add, new CodePrimitiveExpression(1));
loopStatement.IncrementStatement = incrementStatement;
loopStatement.TestExpression = new CodeBinaryOperatorExpression(iReference, CodeBinaryOperatorType.LessThan, iterationLimit);
CodeVariableReferenceExpression consoleRef = new CodeVariableReferenceExpression("Console");
CodeExpression[] args = new CodeExpression[] { iReference };
CodeMethodInvokeExpression consoleWriteLineStmt = new CodeMethodInvokeExpression(consoleRef, "WriteLine", args);
loopStatement.Statements.Add(consoleWriteLineStmt);
ifStatement.TrueStatements.Add(loopStatement);
return ifStatement;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.