C#.Net在IF条件下传递字符串并进行编译 [英] C#.Net Pass String in IF condition and compile it

查看:236
本文介绍了C#.Net在IF条件下传递字符串并进行编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友,

我想在if条件下编译OR执行字符串。我有一个字符串,其中包含类似条件的语句。



例如:

  string  test =   2> 4; 
if (test)
{ // 做某事
}
否则
{}



我想运行这种类型的代码。



提前致谢。

GAURAV MODI



HI JF2015,

感谢您的回复,但我不想要数学解析器。它可以是字符串。



就像我的字符串可能是:('abc'=='as')&&(122> 34)

所以在我们的场景中它是错误的。 />
所以我们的其他部分将被调用。

解决方案

你需要的是一个数学表达式解析器。例如这些:

带插件的可扩展数学表达式解析器 [ ^ ]

数学表达式评估员 [ ^ ]

http://www.bestcode.com /html/bcparser_net.html [ ^ ]


我有几篇关于值转换器的文章用于评估表达式。他们应该有所帮助,他们指出其他选择。我通常使用Javascript eval函数。还有一篇关于使用Roslyn的文章。



用于评估用户公式输入的值转换器 [ ^ ]



使用Roslyn ScriptEngine为ValueConverter处理用户输入 [ ^ ]



这些应该有帮助


您可以使用创建自己的动态LINQ解析器 [ ^ ] d在表达式中留下 obj。



用法:

< pre lang =cs> public class MyClass
{
字符串 StateName { get ; private set ; }
string CityName { get ; private set ; }
...
}
...
string expr = StateName!= \Test \&& CityName!= \AZ \;
var f = SimpleExpression.PredicateParser< MyClass> .Parse(expr).Compile();
var query = 来自 e myCollection 其中 f(e)选择 e;
...
foreach var item 查询中)
{
...
}





干杯

Andi


Hello friends,
I want to compile OR execute string in if condition.I have a string which contains the statement like conditions.

For Example:

string test="2>4";
if(test)
{//do something
}
else
{}


I want run this type of code.

Thanks in advance.
GAURAV MODI

HI JF2015,
Thanks for your reply,but i don't want mathematical parser.it can be string.

like my string may be of : "('abc'=='as')&&(122>34)"
so in our scenario it is wrong.
so our else part will be called.

解决方案

What you need is a mathematical expression parser. For example these ones:
An extensible math expression parser with plug-ins[^]
Inside the Mathematical Expressions Evaluator[^]
http://www.bestcode.com/html/bcparser_net.html[^]


I have several articles on value converters for evaluating expressions. they should be helpful, and they point to other options. I generally used the Javascript eval function. There is also an article on using Roslyn.

Value Converter to Evaluate User Equation Input[^]

Using Roslyn ScriptEngine for a ValueConverter to process user input[^]

These should help


You may use Invent your own Dynamic LINQ parser[^] and leave the obj. in your expression away.

Usage:

public class MyClass
{
   string StateName { get; private set; }
   string CityName  { get; private set; }
   ...
}
...
string expr = "StateName != \"Test\" && CityName != \"AZ\"";
var f = SimpleExpression.PredicateParser<MyClass>.Parse(expr).Compile();
var query = from e in myCollection where f(e) select e;
...
foreach(var item in query)
{
   ...
}



Cheers
Andi


这篇关于C#.Net在IF条件下传递字符串并进行编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆