《CodeDom初体验》一文介绍了如何利用CodeDOM自动生成C#的HelloWorld。本文会关注如何利用CodeDOM和动态语言IronPython来编译和执行HelloWorld。
import sys
import clr
from System import *
from System.IO import *
from System.Reflection import *
from System.CodeDom import *
from System.CodeDom.Compiler import *
from Microsoft.CSharp import *
streamReader = StreamReader( "HelloWorld.cs")
source = streamReader.ReadToEnd()
compilerParam = CompilerParameters()
compilerParam.GenerateInMemory = True
codeProvider = CSharpCodeProvider()
compileResult = codeProvider.CompileAssemblyFromSource(compilerParam, source)
errors = compileResult.Errors
if errors.Count == 0:
asm = compileResult.CompiledAssembly
types = asm.GetTypes()
for type in types:
methods = type.GetMethods()
for method in methods:
if method.IsStatic and method.IsPublic and method.Name == "Main":
method.Invoke(None, None)
import clr
from System import *
from System.IO import *
from System.Reflection import *
from System.CodeDom import *
from System.CodeDom.Compiler import *
from Microsoft.CSharp import *
streamReader = StreamReader( "HelloWorld.cs")
source = streamReader.ReadToEnd()
compilerParam = CompilerParameters()
compilerParam.GenerateInMemory = True
codeProvider = CSharpCodeProvider()
compileResult = codeProvider.CompileAssemblyFromSource(compilerParam, source)
errors = compileResult.Errors
if errors.Count == 0:
asm = compileResult.CompiledAssembly
types = asm.GetTypes()
for type in types:
methods = type.GetMethods()
for method in methods:
if method.IsStatic and method.IsPublic and method.Name == "Main":
method.Invoke(None, None)
大致步骤如下:
1. 通过StreamReader加载源码
2. 通过CSharpCodeProvider编译源码
3. 在编译的Assembly中查找入口函数Main
4. 执行
通过这个例子我们不仅体会了CodeDOM的编译能力,也感受了IronPython的动态绑定特性。如果以后有IronPython和C#的交叉开发,这可能就会是个雏型。
转载于:https://blog.51cto.com/bj007/345676