字符串转换为三元运算符

时间:2016-02-28 10:22:20

标签: c# asp.net

string str= "6 < 5 ? 1002 * 2.5: 6 < 10 ? 1002 * 3.5: 1002 * 4";
double Amount = str;

我想要输出:3507

1 个答案:

答案 0 :(得分:4)

这应解决它:

static void Main(string[] args)
{
    string str = "6 < 5 ? 1002 * 2.5: 6 < 10 ? 1002 * 3.5: 1002 * 4";

    Console.WriteLine(EvaluateExpression(str));
    Console.ReadKey();
}

public static object EvaluateExpression(string expression)
{
    var csc = new CSharpCodeProvider();
    var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" });
    parameters.GenerateExecutable = false;
    CompilerResults results = csc.CompileAssemblyFromSource(new CompilerParameters(new[] { "System.Core.dll" }),
        @"using System;

        class Program
        {
            public static object GetExpressionValue()
            {
                return " + expression + @";
            }
        }");

    if (results.Errors.Count == 0)
    {
        return results.CompiledAssembly.GetType("Program").GetMethod("GetExpressionValue").Invoke(null, null);
    }
    else
    {
        return string.Format("Error while evaluating expression: {0}", string.Join(Environment.NewLine, results.Errors.OfType<CompilerError>()));
    }
}

虽然我建议的东西不那么“脆弱”,但我确信有些图书馆可以帮助你。

答案基于this