| Код | using System; using System.IO; using System.CodeDom.Compiler; using Microsoft.CSharp; using System.Reflection;
namespace ConsoleApplication { class Class1 { [STAThread] static void Main(string[] args) {
// C# исходник для компиляции string source = @" using System;
namespace Test { public class Calculator { public static int Calculate(int x) { return x*x + 10; } } } ";
// путь к длл, учитывая что она уже может существовать // и быть заблокированной string outputPath = @"c:\dynassembly.dll"; int i=2; while(File.Exists(outputPath)) outputPath = @"c:\dynassembly" + (i++).ToString() + ".dll";
// компиляция CompilerParameters compilerParams = new CompilerParameters(); compilerParams.CompilerOptions = "/o /target:library /d:DEBUG;TRACE"; compilerParams.OutputAssembly = outputPath; new CSharpCodeProvider().CreateCompiler().CompileAssemblyFromSource(compilerParams, source);
// загрузка assembly Assembly assm = Assembly.LoadFrom(outputPath); Type t = assm.GetType("Test.Calculator"); MethodInfo method = t.GetMethod("Calculate", BindingFlags.Public|BindingFlags.Static); // вызов Calculate() для нескольких значений X for(int x=0; x<10; x++) { int result = (int)method.Invoke(null, new object[] {x}); Console.WriteLine(result.ToString()); } } } }
| |