c# - C# 计算字符串表达式并返回结果
问题描述
试图找出在 .net/C# 中使用哪种方法来评估运行时的简单表达式。代码必须符合 .net 标准,并且我不想要奇怪的依赖。
我已经研究过使用 Microsoft.CodeAnalysis.CSharp.Scripting: 如何动态评估 C# 代码?但对于我的用例来说,这似乎有点过分了。
public class Evaluate
{
private Dictionary<string, object> _exampleVariables = new Dictionary<string, object>
{
{"x", 45},
{"y", 0},
{"z", true}
};
private string _exampleExpression = "x>y || z";
private string _exampleExpression2 = @"if(x>y || z) return 10;else return 20;
";
public object Calculate(Dictionary<string, object> variables, string expression)
{
var result = //Magical code
return result;
}
}
解决方案
在 C# 中,您可以这样做:
class Program
{
private static Func<Dictionary<string, object>, object> function1 = x =>
{
return ((int)x["x"] > (int)x["y"]) || (bool)x["z"];
};
private static Func<Dictionary<string, object>, object> function2 = x =>
{
if (((int)x["x"] > (int)x["y"]) || (bool)x["z"])
{
return 10;
}
else
{
return 20;
}
};
static void Main(string[] args)
{
Dictionary<string, object> exampleVariables = new Dictionary<string, object>
{
{"x", 45},
{"y", 0},
{"z", true}
};
Console.WriteLine(Calculate(exampleVariables, function2));
}
public static object Calculate(Dictionary<string, object> variables, Func<Dictionary<string, object>, object> function)
{
return function(variables);
}
}
推荐阅读
- angular - Jhipster jenkins:NaN 中的错误但它们指向不同的模块 Webpack 无法区分上下文并且无法加载
- html - 如何配置我的 html 来播放视频 youtube?
- sql - 使用每个 sql SELECT 结果,执行 UPDATE
- memory - MIPS 架构填充
- pyspark - 如何在 Windows 的虚拟环境中让 pyspark 在 Jupyter Notebook 中工作?
- .net - 在启用了身份/身份验证的 .Net 5 的 EF Core 中播种数据时出现问题
- r - 这个 plot_normal_distribution 函数可以优化吗?
- android - .iml 文件可以在没有相应 gradle 依赖项的情况下将数据拉入项目吗?
- dapper - 简洁的一对多映射逻辑
- r - 使用重复循环的斐波那契数