检索在函数求执行被调用的方法的名称
-
22-07-2019 - |
题
我想获得正被授权为函数求的方法的名称。
Func<MyObject, object> func = x => x.DoSomeMethod();
string name = ExtractMethodName(func); // should equal "DoSomeMethod"
我怎样才能做到这一点?
- 对于吹牛的权利 -
请ExtractMethodName
也有一个属性调用工作,有它在该实例返回属性的名称。
例如
Func<MyObject, object> func = x => x.Property;
string name = ExtractMethodName(func); // should equal "Property"
解决方案
看马!没有表达式树!
下面是从底层拉姆达的IL流抓住元数据标记和解决它。一个快速,肮脏和特定于实现的版本
private static string ExtractMethodName(Func<MyObject, object> 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<MyObject, object> func = x => x.DoSomeMethod(x.DoSomeOtherMethod());
您会期待什么?
这就是说,你可以使用反射来开拓Func键对象,看看它里面,但你只能够解决它的某些情况下。
下面看看我劈答案:
为什么会出现不`fieldof `或`在C#methodof`操作者?
在过去我这样做是另一种方式是使用Func
代替Expression<Func<...>>
,但我为这个结果高兴的要少得多。所使用的MemberExpression
检测我fieldof
方法中的字段将返回当使用特性的PropertyInfo
。
编辑#1:这适用于该问题的一个子集:
Func<object> func = x.DoSomething;
string name = func.Method.Name;
编辑#2:谁标志着我失望应采取第二意识到这里发生了什么上。该表达式树可以用lambda表达式被隐式使用,并以最快,最可靠的方法来获得特定要求的信息在这里。
不隶属于 StackOverflow