简体   繁体   English

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

[英]C# evaluate a string expression and return the result

Trying to figure out which approach to use in .net/C# to evaluate a simple expression in runtime. 试图找出在.net / C#中使用哪种方法来评估运行时中的简单表达式。 Code must be .net standard compliant, and I dont want weird dependecies. 代码必须符合.net标准,我不想要奇怪的依赖。

I have looked into using using Microsoft.CodeAnalysis.CSharp.Scripting: How can I evaluate C# code dynamically? 我已经研究过使用Microsoft.CodeAnalysis.CSharp.Scripting: 如何动态评估C#代码? but it seems overkill for my use case. 但对我的用例来说似乎有些过分。

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

In C# you can do this: 在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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM