1
string str= "6 < 5 ? 1002 * 2.5: 6 < 10 ? 1002 * 3.5: 1002 * 4";
double Amount = str;
我想输出:3507字符串转换为三元运算符
string str= "6 < 5 ? 1002 * 2.5: 6 < 10 ? 1002 * 3.5: 1002 * 4";
double Amount = str;
我想输出:3507字符串转换为三元运算符
这应该解决这个问题:
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。
感谢您的编辑 –
有很多方法可以运行C#代码:[http://stackoverflow.com/questions/4181668/execute-c-sharp-code-at-runtime-from-code-文件(http://stackoverflow.com/questions/4181668/execute-c-sharp-code-at-runtime-from-code-file) –