4

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”而不是这个字符串。

我想我可以做一个解析方法,逐步减少字符串,直到我们得到最终值,但我想知道是否有更好的方法。

4

4 回答 4

10

扩展 Rob 的评论,您可以将运行时编译与 C# 4.0dynamic支持结合使用,并执行以下操作:

var expression = "(true and false) or (true or false)";

var helper = "" + 
    "using System; " + 
    "public class Expression {{ public bool Eval() {{ return {0}; }} }}";

var replaced = expression.Replace("and", "&&").Replace("or", "||");

var references = new string[] { "System.dll" };
var parameters = new CompilerParameters(references, "Test.dll");
var compiler = new CSharpCodeProvider();


var results = compiler.CompileAssemblyFromSource(
    parameters, 
    String.Format(helper, replaced));

dynamic exp = Activator.CreateInstance(
    results.CompiledAssembly.GetType("Expression"));

Console.WriteLine(exp.Eval());
于 2011-06-07T15:07:56.457 回答
7

可能是这样的?

string previous = string.Empty;
while (b != previous) 
{
     previous = b;
     b = b.Replace("true and false", "false");
     b = b.Replace("true and true", "true");
     b = b.Replace("false and true", "false");
     b = b.Replace("false and false", "false");
     b = b.Replace("false or false", "false");
     b = b.Replace("true or false", "true");
     b = b.Replace("true or true", "true");
     b = b.Replace("false or true", "true");
     b = b.Replace("(false)", "false");
     b = b.Replace("(true)", "true");
     b = b.Replace("not false", "true");
     b = b.Replace("not true", "false");
 }

请注意,规范允许模棱两可的表述,例如:

"false and false or true"
"false and true or true"

如果首先计算和,则这两个表达式都是“真”,如果首先计算,则这两个表达式都是“假” 。因此,在每个级别都需要括号会更好。要求从左到右求值是另一种选择,但这会使代码更复杂一些。

对于那些可能反对这种类型的问题的解决方案的人,请记住,一些数学家认为所有的数学都可能被简化为这种符号操作。据说,对罗素和怀特黑德的《数学原理》的主要批评之一是它包含了太多意义的公式。

于 2011-06-07T14:42:50.620 回答
2

解析是你最好的选择。如果您必须检查拼写错误,那将变得更加困难。

于 2011-06-07T14:40:35.133 回答
-1

C# 没有 Eval 方法或类似的方法,可以让您只运行这样的语句来获得最终结果。除非我遗漏了一些东西,否则你将不得不解析并减少这种方式。

于 2011-06-07T14:40:27.907 回答