3 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超8個(gè)贊
是! 使用在Microsoft.CSharp,System.CodeDom.Compiler和System.Reflection命名空間中找到的方法。這是一個(gè)簡(jiǎn)單的控制臺(tái)應(yīng)用程序,它使用一個(gè)方法(“ Add42”)編譯一個(gè)類(“ SomeClass”),然后允許您調(diào)用該方法。這是一個(gè)簡(jiǎn)單的示例,我對(duì)其進(jìn)行了格式化,以防止?jié)L動(dòng)條出現(xiàn)在代碼顯示中。這只是為了演示在運(yùn)行時(shí)編譯和使用新代碼。
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();
}
}
}
- 3 回答
- 0 關(guān)注
- 560 瀏覽
添加回答
舉報(bào)