如何获取匿名方法的源代码?
例如:
Func<Boolean> func = (() => DateTime.Now.Seconds % 2 == 0);
Console.WriteLine(GetSourceCode(func)); // must: DateTime.Now.Seconds % 2 == 0
String GetSourceCode<T>(Func<T> f) - ???
答案 0 :(得分:6)
你可以将它包装在Expression中并在其上调用ToString(),这将获得源代码。
像这样:
Expression<Func<Boolean>> func = (() => DateTime.Now.Seconds % 2 == 0);
var str = func.ToString();
输出str成为
() => DateTime.Now.Seconds % 2 == 0