《CodeDom初体验》一文介绍了如何利用CodeDOM自动生成C#的HelloWorld。本文会关注如何利用CodeDOM和动态语言IronPython来编译和执行HelloWorld。
InBlock.gifimport sys
InBlock.gifimport clr
InBlock.giffrom System import *
InBlock.giffrom System.IO import *
InBlock.giffrom System.Reflection import *
InBlock.giffrom System.CodeDom import *
InBlock.giffrom System.CodeDom.Compiler import *
InBlock.giffrom Microsoft.CSharp import *
InBlock.gifstreamReader = StreamReader( "HelloWorld.cs")
InBlock.gifsource = streamReader.ReadToEnd()
InBlock.gifcompilerParam = CompilerParameters()
InBlock.gifcompilerParam.GenerateInMemory = True
InBlock.gifcodeProvider = CSharpCodeProvider()
InBlock.gifcompileResult = codeProvider.CompileAssemblyFromSource(compilerParam, source)
InBlock.giferrors = compileResult.Errors
InBlock.gif if errors.Count == 0:
InBlock.gif        asm = compileResult.CompiledAssembly
InBlock.gif        types = asm.GetTypes()
InBlock.gif         for type in types:
InBlock.gif                methods = type.GetMethods()
InBlock.gif                 for method in methods:
InBlock.gif                         if method.IsStatic and method.IsPublic and method.Name == "Main":
InBlock.gif                                    method.Invoke(None, None)

大致步骤如下:
1. 通过StreamReader加载源码
2. 通过CSharpCodeProvider编译源码
3. 在编译的Assembly中查找入口函数Main
4. 执行
  通过这个例子我们不仅体会了CodeDOM的编译能力,也感受了IronPython的动态绑定特性。如果以后有IronPython和C#的交叉开发,这可能就会是个雏型。