「メモ」の編集履歴(バックアップ)一覧に戻る
メモ - (2008/10/16 (木) 16:37:30) のソース
*C#で文字列からアセンブリを動的に生成する方法 #highlight(){ Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider(); System.CodeDom.Compiler.CompilerParameters parameters = new System.CodeDom.Compiler.CompilerParameters( new string[] { "Boare.Lib.Vsq.dll" } ); parameters.GenerateInMemory = true; string code = "using Boare.Lib.Vsq;namespace a{public class foo{public static ulong bar(VsqFile vsqFile){return vsqFile.TotalClocks;}}}"; System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromSource( parameters, code ); if ( results.Errors.Count != 0 ) { for ( int i = 0; i < results.Errors.Count; i++ ) { Console.WriteLine( " error=" + results.Errors[i].ErrorText ); } throw new ApplicationException( "Errors.Count=" + results.Errors.Count ); } System.Reflection.Assembly testAssembly = results.CompiledAssembly; Type fooType = testAssembly.GetType( "a.foo" ); System.Reflection.MethodInfo mi = fooType.GetMethod( "bar" ); GetTotalClocksDelegate gtcd = (GetTotalClocksDelegate)Delegate.CreateDelegate( typeof( GetTotalClocksDelegate ), mi ); Console.WriteLine( "fooInstance.bar()=" + gtcd.Invoke( m_config.VsqFile ) ); ----