检索在Func中执行的调用方法的名称

我想获得被委派为Func的方法的名称。

Func func = x => x.DoSomeMethod(); string name = ExtractMethodName(func); // should equal "DoSomeMethod" 

我怎样才能做到这一点?

– 吹牛的权利 –

Make ExtractMethodName也可以使用属性调用,让它返回该实例中的属性名称。

例如。

 Func func = x => x.Property; string name = ExtractMethodName(func); // should equal "Property" 

看马! 没有表达树!

这是一个快速,脏和特定于实现的版本,它从底层lambda的IL流中获取元数据令牌并解析它。

 private static string ExtractMethodName(Func func) { var il = func.Method.GetMethodBody().GetILAsByteArray(); // first byte is ldarg.0 // second byte is callvirt // next four bytes are the MethodDef token var mdToken = (il[5] << 24) | (il[4] << 16) | (il[3] << 8) | il[2]; var innerMethod = func.Method.Module.ResolveMethod(mdToken); // Check to see if this is a property getter and grab property if it is... if (innerMethod.IsSpecialName && innerMethod.Name.StartsWith("get_")) { var prop = (from p in innerMethod.DeclaringType.GetProperties() where p.GetGetMethod() == innerMethod select p).FirstOrDefault(); if (prop != null) return prop.Name; } return innerMethod.Name; } 

在一般情况下,我认为这是不可能的。 如果你有:

 Func func = x => x.DoSomeMethod(x.DoSomeOtherMethod()); 

你会期待什么?

话虽这么说,你可以使用reflection来打开Func对象并查看其内部的作用,但是你只能在某些情况下解决它。

看看我的黑客答案:

为什么C#中没有`fieldof`或`methodof`运算符?

在过去,我采用另一种方式使用Func而不是Expression> ,但我对结果不太满意。 用于检测fieldof方法中的字段的fieldof将在使用PropertyInfo时返回PropertyInfo

编辑#1:这适用于问题的一个子集:

 Func func = x.DoSomething; string name = func.Method.Name; 

编辑#2:谁标记我应该花一秒钟才能意识到这里发生了什么。 表达式树可以隐式地与lambda表达式一起使用,并且是在这里获取特定请求信息的最快,最可靠的方法。