如何通过CodeDOM或LinqExpression动态生成if条件块?
if ((x == 1 && y == "test") || str.Contains("test"))
...
如何使用 C# 通过 CodeDOM 或 LinqExpression 动态生成 if 块中的条件?
if ((x == 1 && y == "test") || str.Contains("test"))
...
how to generate condition in the if block by CodeDOM or LinqExpression Dynamiclly with C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
要允许您使用纯 CodeDom 创建表达式,您可以在
CodeConditionStatement
内使用CodeBinaryOperationExpression
。条件如下所示:
那么您所需要的就是 true 和 false 语句:
然后将它们全部放在
if
语句中:创建一个类的完整示例,该类的方法为执行评估可能如下所示:
使用此代码在 C# 中生成源输出...
...
sourceCode
将包含:将提供程序从
csharp
更改为vb
得到这个:To allow you to use pure CodeDom for creating the expression you can use the
CodeBinaryOperationExpression
inside theCodeConditionStatement
.The condition would look like this:
So then all you need are the true, and optionally false, statements:
Then put it all together in the
if
statement:The complete sample to create a class with a method that performs the evaluation could look like this:
Generate source output in C# using this code...
...
sourceCode
will contain:Change the provider from
csharp
tovb
to get this:要使用 codedom 创建上面的动态代码,您需要执行以下操作:
创建一个可以添加到类中的方法:
创建一个 If 命令,包括括号内的语句,例如
{Value = 4;}
:将 If 命令添加到上面创建的方法中:
To create the code above dynamical using codedom you need to do the following:
Create a Method which can be added to a class:
Create a If command including statement inside the brackets eg
{Value = 4;}
:Add the If command to the method which was created above: