首页 > 解决方案 > 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#stringdynamiclogicexpression

解决方案


在 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);
    }
}

推荐阅读