C# 动态计算表达式的值--动态编译和DataTable.Compute()

        public static void TestComput(string expression)
        {
            //要编译的代码段
            string code = @"public class TestCompute
{public static object Compute()
{return @exp;}}";
            code = code.Replace("@exp", expression);


            CSharpCodeProvider csharpCodeProvider = new CSharpCodeProvider();
            CompilerParameters compilerParameters = new CompilerParameters();
            //compilerParameters.CompilerOptions = "/t:library";
            //compilerParameters.GenerateInMemory = true;
            //开始编译
            CompilerResults compilerResults = csharpCodeProvider.CompileAssemblyFromSource(compilerParameters, code);
            if (compilerResults.Errors.Count > 0)
                throw new Exception("编译出错!");
            Assembly assembly = compilerResults.CompiledAssembly;
            Type type = assembly.GetType("TestCompute");

            //使用动态编译计算表达式
            object obj = type.GetMethod("Compute").Invoke(null, null);

            //使用DataTable的Compute也可以计算一些简单的表达式
            DataTable dt = new DataTable();
            obj = dt.Compute(expression, null);
        }


你可能感兴趣的:(c#)