在C#中,我可以使用表达式树很容易地创建对象图的字符串表示.
public static string GetGraph<TModel, T>(TModel model, Expression<Func<TModel, T>> action) where TModel : class
{
var method = action.Body as MethodCallExpression;
var body = method != null ? method.Object != null ? method.Object as MemberExpression : method.Arguments.Any() ? method.Arguments.First() as MemberExpression : null : action.Body as MemberExpression;
if (body != null)
{
string graph = GetObjectGraph(body, typeof(TModel))
return graph;
}
throw new Exception("Could not create object graph");
}
Run Code Online (Sandbox Code Playgroud)
在F#中我一直在看引文试图做同样的事情,并且无法弄明白.我曾尝试使用PowerPack库将引用转换为Expression,但到目前为止还没有运气,而且互联网上的信息在这个主题上看起来相当稀少.
如果输入是:
let result = getGraph myObject <@ myObject.MyProperty @>
Run Code Online (Sandbox Code Playgroud)
输出应为"myobject.MyProperty"
您可以在fsi会话中看到从引号表达式中获得的内容:
> let v = "abc"
> <@ v.Length @>;;
val it : Expr<int>
= PropGet (Some (PropGet (None, System.String v, [])), Int32 Length, [])
> <@ "abc".Length @>;;
val it : Expr<int>
= PropGet (Some (Value ("abc")), Int32 Length, [])
Run Code Online (Sandbox Code Playgroud)
您可以找到可用于解析qoutations的所有活动模式的描述
手动\ FSharp.Core\Microsoft.FSharp.Quotations.Patterns.html
在您的F#安装目录下或在msdn站点下
有很好的Chris Smith的书"Programming F#",章节名为"Quotations":)
所以,毕竟,只是尝试编写简单的解析器:
open Microsoft.FSharp.Quotations
open Microsoft.FSharp.Quotations.Patterns
open Microsoft.FSharp.Quotations.DerivedPatterns
let rec getGraph (expr: Expr) =
let parse args =
List.fold_left (fun acc v -> acc ^ (if acc.Length > 0 then "," else "") ^ getGraph v) "" args
let descr s = function
| Some v -> "(* instance " ^ s ^ "*) " ^ getGraph v
| _ -> "(* static " ^ s ^ "*)"
match expr with
| Int32 i -> string i
| String s -> sprintf "\"%s\"" s
| Value (o,t) -> sprintf "%A" o
| Call (e, methodInfo, av) ->
sprintf "%s.%s(%s)" (descr "method" e) methodInfo.Name (parse av)
| PropGet(e, methodInfo, av) ->
sprintf "%s.%s(%s)" (descr "property" e) methodInfo.Name (parse av)
| _ -> failwithf "I'm don't understand such expression's form yet: %A" expr
Run Code Online (Sandbox Code Playgroud)
PS当然,您需要一些代码才能将AST转换为人类可读的格式.