C#动态编译

要用到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 @ 2022-07-27 14:03  devgis  阅读(188)  评论(0编辑  收藏  举报