栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

是! 使用在Microsoft.CSharp,System.CodeDom.Compiler和System.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();        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/421510.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号