您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

.NET是否可以在运行时编译和执行新代码?

.NET是否可以在运行时编译和执行新代码?

是! 使用在Microsoft.CSharpSystem.CodeDom.CompilerSystem.Reflection命名空间中找到的方法。这是一个简单的控制台应用程序,它使用一个方法(“ Add42”)编译一个类(“ SomeClass”),然后允许您调用方法。这是一个简单的示例,我对其进行了格式化,以防止滚动条出现在代码显示中。这只是为了演示在运行时编译和使用新代码

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

namespace RuntimeCompilationTest {
    class Program
    {
        static void Main(string[] args) {
            string sourceCode = @"
                public class SomeClass {
                    public int Add42 (int parameter) {
                        return parameter += 42;
                    }
                }";
            var compParms = new CompilerParameters{
                GenerateExecutable = false, 
                GenerateInMemory = true
            };
            var csProvider = new CSharpCodeProvider();
            CompilerResults compilerResults = 
                csProvider.CompileAssemblyFromSource(compParms, sourceCode);
            object typeInstance = 
                compilerResults.CompiledAssembly.CreateInstance("SomeClass");
            MethodInfo mi = typeInstance.GetType().getmethod("Add42");
            int methodOutput = 
                (int)mi.Invoke(typeInstance, new object[] { 1 }); 
            Console.WriteLine(methodOutput);
            Console.ReadLine();
        }
    }
}
dotnet 2022/1/1 18:14:21 有634人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶