C#计算字符串表达式并返回结果

时间:2019-06-13 12:33:07

标签: c# string dynamic logic expression

试图弄清楚在.net / C#中使用哪种方法来评估运行时的简单表达式。代码必须符合.net标准,我不希望有奇怪的依赖。

我研究了使用Microsoft.CodeAnalysis.CSharp.Scripting的方法: How can I evaluate C# code dynamically?,但对于我的用例来说似乎有些过分。

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

1 个答案:

答案 0 :(得分:0)

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