c#将字符串表达式转换为布尔表达式 [英] c# convert string expression to a boolean expression

查看:34
本文介绍了c#将字符串表达式转换为布尔表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将字符串表达式转换为布尔条件?

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"

我想从中创建一个 bool 表达式并调用它.字符串表示也很灵活(为了让它更有趣),所以它允许 ||, &&, ().

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 ||, &&, ().

推荐答案

我会使用 Irony,.NET 语言工具包.您可以使用 Irony 构建一个简单的语法,然后将字符串解析为可执行命令.在这个教程Expression Grammar Sample,这是一个很常见的请求;)

I would use Irony, the .NET language kit. You could construct a simple grammar with Irony and then parse the string into executable command. There's a decent example of an arthmetic grammar in this tutorial and in the Expression Grammar Sample, its a pretty common request ;)

我绝对建议使用适当的编译器,而不是 Regex 或使用自己的方法 - 如果您想添加更多规则,它会更具可扩展性.

I definitely suggest using a proper compiler as opposed to Regex or a roll your own approach - it will be much more extensible if you ever want to add more rules.

这篇关于c#将字符串表达式转换为布尔表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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