// namespaceを取得
String ns = this.GetType().Namespace;
// ClassAのTypeを取得
Type type = Type.GetType(String.Format("{0}.{1}", ns, "ClassA"), false);
// ClassAのインスタンス作成
ClassA a = Activator.CreateInstance(type) as ClassA;
↑は既にクラスを定義してあり、アセンブリも読み込んでいる必要があるが、 文字列から動的にクラス自体を作ることも出来る。プログラムからソース・コードをコンパイルして実行するには?
必要な部分だけ抜粋しておく。
using System;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
using System.Reflection;
public class CompileInvoke {
static string cs = @"
public class CSHello {
public static void Main() {
System.Console.WriteLine(""Hello C# World!"");
}
}";
public static void Main() {
CSharpCodeProvider cscp = new CSharpCodeProvider();
ICodeCompiler cc = cscp.CreateCompiler();
CompilerParameters param = new CompilerParameters();
param.GenerateInMemory = true;
CompilerResults cr = cc.CompileAssemblyFromSource(param, cs);
Assembly asm = cr.CompiledAssembly;
Type type = asm.GetType("CSHello");
MethodInfo mi = type.GetMethod("Main");
mi.Invoke(null, null); // 出力:Hello C# World!"
}
}
0 件のコメント:
コメントを投稿