使用方法调用很容易从lambda转到Expression
public void GimmeExpression(Expression<Func<T>> expression)
{
((MemberExpression)expression.Body).Member.Name; // "DoStuff"
}
public void SomewhereElse()
{
GimmeExpression(() => thing.DoStuff());
}
Run Code Online (Sandbox Code Playgroud)
但我想将Func转换为表达式,仅在极少数情况下......
public void ContainTheDanger(Func<T> dangerousCall)
{
try
{
dangerousCall();
}
catch (Exception e)
{
// This next line does not work...
Expression<Func<T>> DangerousExpression = dangerousCall;
var nameOfDanger =
((MemberExpression)dangerousCall.Body).Member.Name;
throw new DangerContainer(
"Danger manifested while " + nameOfDanger, e);
}
}
public void SomewhereElse()
{
ContainTheDanger(() => thing.CrossTheStreams());
}
Run Code Online (Sandbox Code Playgroud)
不起作用的行给了我编译时错误Cannot implicitly convert type 'System.Func<T>' to 'System.Linq.Expressions.Expression<System.Func<T>>'.显式强制转换无法解决问题.我有一个设施可以做到这一点吗?
有没有办法将现有的Func委托转换为这样的字符串:
Func<int, int> func = (i) => i*2;
string str = someMethod(func); // returns "Func<int, int> func = (i) => i*2"
Run Code Online (Sandbox Code Playgroud)
或者至少接近它