编译并调用生成的方法

发布于 2024-07-07 05:12:56 字数 110 浏览 5 评论 0原文

我设法使用 CodeDom 创建一个类,并向该类添加一个方法。 现在,有没有办法在构造了 CodeCompileUnit 实例后,编译代码并调用生成的方法? 方法调用必须在与代码生成相同的上下文中完成。

I managed to create a class using CodeDom and add a single method to that class. Now, is there a way to, having constructed the CodeCompileUnit instance, compile the code and invoke the generated method? The method invocation has to be done in the same context as the code generation.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失去的东西太少 2024-07-14 05:12:56

摘自我的朋友的博客

    CSharpCodeProvider codeProvider = new CSharpCodeProvider();
    codeProvider.GenerateCodeFromNamespace(codeNamespace, new StringWriter(), new CodeGeneratorOptions());

    CompilerParameters param = new CompilerParameters(assemblyReferences);
    param.GenerateExecutable = false;
    param.GenerateInMemory = true;
    param.TreatWarningsAsErrors = false;
    param.WarningLevel = 4;

    CompilerResults results = codeProvider.CompileAssemblyFromDom(param, compileUnit);
    Assembly assembly = results.CompiledAssembly;

    Type[] types = assembly.GetExportedTypes();

然后您可以使用反射在类型上创建所需类型的实例并执行所需的任何方法。

Taken from a friend of mine's blog:

    CSharpCodeProvider codeProvider = new CSharpCodeProvider();
    codeProvider.GenerateCodeFromNamespace(codeNamespace, new StringWriter(), new CodeGeneratorOptions());

    CompilerParameters param = new CompilerParameters(assemblyReferences);
    param.GenerateExecutable = false;
    param.GenerateInMemory = true;
    param.TreatWarningsAsErrors = false;
    param.WarningLevel = 4;

    CompilerResults results = codeProvider.CompileAssemblyFromDom(param, compileUnit);
    Assembly assembly = results.CompiledAssembly;

    Type[] types = assembly.GetExportedTypes();

You can then use reflection on the types to create an instance of the type you want and execute whatever method you want.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文