wil*_*arg 2 linq ironpython expression-trees
我使用此代码使用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);
Run Code Online (Sandbox Code Playgroud)
有没有办法将生成的表达式树作为c#对象,例如BlockExpression
?
IronPython的内部AST也恰好是Expression树,因此您只需要为您的代码获取AST,您可以使用IronPython.Compiler.Parser
该类来完成.Parser.ParseFile方法将返回IronPython.Compiler.Ast.PythonAst
表示代码的实例.
使用解析器有点棘手,但您可以查看_ast模块的BuildAst
方法以获取一些提示.基本上,它是:
Parser parser = Parser.CreateParser(
new CompilerContext(sourceUnit, opts, ThrowingErrorSink.Default),
(PythonOptions)context.LanguageContext.Options);
PythonAst ast = parser.ParseFile(true);
Run Code Online (Sandbox Code Playgroud)
ThrowingErrorSink
也来自_ast
模块.你可以得到一个SourceUnit
像这样的实例(cf compile
builtin):
SourceUnit sourceUnit = context.LanguageContext.CreateSnippet(source, filename, SourceCodeKind.Statements);
Run Code Online (Sandbox Code Playgroud)
然后,您必须遍历AST以从中获取有用的信息,但它们应该与C#表达式树类似(但不相同).
归档时间: |
|
查看次数: |
1209 次 |
最近记录: |