C#动态编译

CSharpCodeProvider objCSharpCodePrivoder = new CSharpCodeProvider();
        CodeDomProvider codedom = CSharpCodeProvider.CreateProvider("C#");

        ICodeCompiler objICodeCompiler = objCSharpCodePrivoder.CreateCompiler();

        CompilerParameters objCompilerParameters = new CompilerParameters();
        objCompilerParameters.ReferencedAssemblies.Add("System.dll");
        objCompilerParameters.GenerateExecutable = false;
        objCompilerParameters.GenerateInMemory = false;

        CompilerResults cr = objICodeCompiler.CompileAssemblyFromSource(objCompilerParameters, @"using System;
                                                                                                public class Test
                                                                                                {
                                                                                                    public object test()
                                                                                                    {
                                                                                                        return 0;
                                                                                                    }
                                                                                                }");
        var p1 = new { Name = "1111", Value = new { V = "222" } };

        if (cr.Errors.HasErrors)
        {
           
        }
        else
        {
            Assembly objAssembly = cr.CompiledAssembly;
            object objHelloWorld = objAssembly.CreateInstance("Test");
            MethodInfo objMI = objHelloWorld.GetType().GetMethod("test");

            var p = objMI.Invoke(objHelloWorld, null);
        }

你可能感兴趣的:(动态编译)