C# 解析“(true and true)或(true or false)”
C#:我有一个字符串变量,如下所示:
string a = "(true and true) or (true or false)";
这可以是任何内容,它可以变得更复杂,例如:
string b = "((true and false) or (true or false) and not (true and false)) and false";
我所知道的是它是正确的。不可能发生这个表达式不能被“评估”的情况。
有什么方法可以让我对此进行评估吗?我只想知道该字符串的结果(结果)。这意味着我需要“true”或“false”而不是这个字符串。
我想我可以创建一个解析方法来执行此操作,逐步减少字符串,直到获得最终值,但我想知道是否有更好的方法。
C#: I have a string variable that looks like this:
string a = "(true and true) or (true or false)";
This can be anything, it can get more complex, like:
string b = "((true and false) or (true or false) and not (true and false)) and false";
All i know is that it is correct. Cannot happen that this expression cannot be "evaluated".
Is there a way that I can somehow evaluate this? I would only like to know the outcome (result) of that string. This means I need "true" or "false" instead of this string.
I think I can make a parse method that does this, reducing the string step by step, until we got the final value, but I was wondering if there is a better approach.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
扩展 Rob 的评论,您可以将运行时编译与 C# 4.0
dynamic
支持结合使用,并执行如下操作:Expanding on Rob's comment, you can use runtime compilation in conjunction with C# 4.0
dynamic
support and do something like this:也许是这样的?
请注意,规范允许不明确的表述,例如:
如果首先评估 and,则这两个表达式均为“true”,如果首先评估 or,则这两个表达式均为“false”第一的。因此,在每个级别都需要括号会更好。要求从左到右求值是另一种选择,但这会使代码变得更加复杂。
对于那些可能反对这种类型问题的解决方案的人,请记住,一些数学家认为所有数学都可以简化为这种符号操作。 说是对罗素和怀特海数学原理<的主要批评之一/em> 是它给公式赋予了太多的含义。
Something like this maybe?
Note that the specification allows ambigious formulations, such as these:
Both of these expressions are "true" if the and is evaluted first, and "false" if the or is evaluated first. Therefore, requireing parenthesis at every level would be better. Requiring left-to-right evaluation is another option, but that makes the code a bit more complex.
For those of you who may object to this style of solution for this style of problem, remember that some mathematicians believe that all of mathematics may be reduced to this sort of symbol manipulation. It is said that one of the main criticisms of Russell and Whitehead’s Principia Mathematica is that it embues the formulas with too much meaning.
解析是你最好的选择。如果你必须检查拼写错误,那就有点困难了。
Parsing is your best bet. If you have to check for typos, that would make it a bit harder.
C# 没有 Eval 方法或类似的方法,可以让您只运行这样的语句来获得最终结果。除非我遗漏了什么,否则你必须以这种方式进行解析和减少。
C# Doesn't have an Eval method or something similar that would allow you to just run a statement like this to gain the final resultant. Unless I'm missing something, you'll have to parse through and reduce that way.