C#动态编译代码

using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;

public class Example
{
    static void Main()
    {
        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerParameters parameter = new CompilerParameters();
        parameter.ReferencedAssemblies.Add("System.dll");
        parameter.GenerateExecutable = false;
        parameter.GenerateInMemory = true;

        CompilerResults result = provider.CompileAssemblyFromSource(parameter,
            CreateCode("256*56*(145+56.0*254/345)"));//将你的式子放在这里
        if (result.Errors.Count > 0)
        {
            Console.WriteLine("动态编译出错了!");
        }
        else
        {
            Assembly assembly = result.CompiledAssembly;
            Type AType = assembly.GetType("ANameSpace.AClass");
            MethodInfo method = AType.GetMethod("AFunc");
            Console.WriteLine(method.Invoke(null, null));
        }
        Console.Read();
    }
    static string CreateCode( string para)
    {
        return "using System; namespace ANameSpace{static class AClass{public static object AFunc(){return "+para+";}}}";
    }
}

posted @ 2011-10-24 16:25  pnljs  阅读(327)  评论(0编辑  收藏  举报