在 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");
}
在 F# 中,我一直在查看引文以尝试做同样的事情,但无法完全弄清楚。我尝试使用 PowerPack 库将引用转换为表达式,但到目前为止没有运气,并且互联网上关于这个主题的信息似乎相当稀疏。
如果输入是:
let result = getGraph myObject <@ myObject.MyProperty @>
输出应该是“myobject.MyProperty”