IronPython中的表达式树

| 我使用此代码使用IronPython执行python表达式。
    ScriptEngine engine = Python.CreateEngine();
    ScriptScope scope = engine.CreateScope();      
    scope.SetVariable(\"m\", mobject);
    string code = \"m.ID > 5 and m.ID < 10\";
    ScriptSource source = 
engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);
    source.Execute(scope);
有没有办法将生成的表达式树作为c#对象,例如
BlockExpression
?     
已邀请:
IronPython的内部AST也恰好是表达式树,因此您只需要获取代码的AST,就可以使用
IronPython.Compiler.Parser
类来完成。 Parser.ParseFile方法将返回一个表示代码的“ 3”实例。 使用解析器有些棘手,但是您可以查看_ast模块的
BuildAst
方法以获得一些提示。基本上是:
Parser parser = Parser.CreateParser(
    new CompilerContext(sourceUnit, opts, ThrowingErrorSink.Default),
    (PythonOptions)context.LanguageContext.Options);

PythonAst ast = parser.ParseFile(true);
ThrowingErrorSink
也来自
_ast
模块。您可以像这样获得
SourceUnit
实例(参见内置的
compile
):
SourceUnit sourceUnit = context.LanguageContext.CreateSnippet(source, filename, SourceCodeKind.Statements);
然后,您必须走动AST才能获得有用的信息,但是它们应该与C#表达式树相似(但不相同)。     

要回复问题请先登录注册