动态编译C#代码

项目开发中,有时候会使用到动态生成代码,然后根据动态生成的代码再执行相应的操作,C#提供了动态代码的编译,利用这个特性可以实现动态生成代码,然后执行代码。
直接上代码,c#版本

[MenuItem("Test/CreateCodeDll")]
    public static void CreateCodeDll1()
    {
        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerParameters parameters = new CompilerParameters();

        parameters.GenerateExecutable = false;
        parameters.GenerateInMemory = false;
        string path = "MyCode.dll";
        parameters.OutputAssembly = path;
        parameters.ReferencedAssemblies.Add("System");

        string sourceFile = @"
            using System;

            public class MyCode
            {
                 public static int Test(int x, int y)
                 {
                     return x+y;
                 }
             }
        ";
        CompilerResults cr = provider.CompileAssemblyFromSource(parameters, sourceFile);

        if (cr.Errors.Count > 0)
        {
            // Display compilation errors.
            Debug.LogError("Errors building " + sourceFile + " into " + cr.PathToAssembly);
            foreach (CompilerError ce in cr.Errors)
            {
                Debug.LogError(ce.ToString());
            }
        }
        else
        {
            Debug.Log("编译成功");
        }

        Assembly ass = cr.CompiledAssembly;
        object obj = ass.CreateInstance("MyCode");
        MethodInfo method = obj.GetType().GetMethod("Test");
        object result = method.Invoke(obj, new object[] { 1, 5 });
        Debug.Log(result);
    }

Unity脚本需要引用Unity自身的Dll类,代码如下

[MenuItem("Test/UnityCreateDll")]
    public static void CreateDll()
    {
        CSharpCodeProvider provider = new CSharpCodeProvider();
        CompilerParameters parameters = new CompilerParameters();

        string dllPath = EditorApplication.applicationContentsPath + "/Managed/";
        Debug.Log(EditorApplication.applicationContentsPath);

        parameters.WarningLevel = 2;
        parameters.GenerateExecutable = false;
        parameters.GenerateInMemory = false;
        string path = "MyCode.dll";
        parameters.OutputAssembly = path;
        parameters.ReferencedAssemblies.Add("System");
        parameters.ReferencedAssemblies.Add(dllPath + "UnityEngine");
     //   parameters.ReferencedAssemblies.Add(dllPath + "UnityEditor");

        string[] sourceFile = new string[] {
            Application.dataPath + "/Test1.cs",
            Application.dataPath + "/Test2.cs"
        };

        CompilerResults cr = provider.CompileAssemblyFromFile(parameters, sourceFile);

        if (cr.Errors.Count > 0)
        {
            // Display compilation errors.
             Debug.LogError("Errors building " + sourceFile + " into " + cr.PathToAssembly);
            foreach (CompilerError ce in cr.Errors)
            {
                Debug.LogError(ce.ToString());
            }
        }
        else
        {
            Debug.Log("编译成功");
        }


          AssetDatabase.Refresh();
    }

这个路径是取得工程目录,也就是Assets目录的上一层目录。

关于这里编译参数的设置见:MSDN
warningLevel的含义见 MSDN

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值