gpt4 book ai didi

C#解析 "(true and true) or (true or false)"

转载 作者:太空狗 更新时间:2023-10-29 23:59:15 25 4
gpt4 key购买 nike

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

我想我可以创建一个解析方法来执行此操作,逐步减少字符串,直到我们获得最终值,但我想知道是否有更好的方法。

最佳答案

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

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());

关于C#解析 "(true and true) or (true or false)",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6266905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com