c# convert string expression to a boolean expressi

2020-01-28 08:46发布

Is it possible to convert a string expression into a boolean condition?

For example, I get the following string:

var b = "32 < 45 && 32 > 20"

I would like to create a bool expression out of this and invoke it. The string representation is also flexible (to make it more fun), so it allows ||, &&, ().

7条回答
太酷不给撩
2楼-- · 2020-01-28 09:13

I think creating an interpreter for this string would not take too long time.

http://www.industriallogic.com/xp/refactoring/implicitLanguageWithInterpreter.html

here you can find information about design that can be used to create it.

查看更多
Root(大扎)
3楼-- · 2020-01-28 09:14

If you're dealing with relatively simple mathematical expressions then a straightforward implementation of the shunting-yard algorithm should do the trick.

查看更多
Emotional °昔
4楼-- · 2020-01-28 09:15

Have a look at Flee (Fast Lightweight Expression Evaluator) on CodePlex.

查看更多
放我归山
5楼-- · 2020-01-28 09:22

If it follows all C# expression rules then compile it as dynamic code as per http://www.west-wind.com/presentations/dynamiccode/dynamiccode.htm

查看更多
神经病院院长
6楼-- · 2020-01-28 09:22

Take a look at my library, Proviant. It's a .NET Standard library using the Shunting Yard algorithm to evaluate boolean expressions. You could also implement your own grammar.

查看更多
唯我独甜
7楼-- · 2020-01-28 09:28

You could take a look at JINT (Javascript Interpreter for .NET) http://jint.codeplex.com/

查看更多
登录 后发表回答