检索在函数求执行被调用的方法的名称 [英] Retrieving the name of the invoked method executed in a Func
本文介绍了检索在函数求执行被调用的方法的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获得正被委托作为函数求法的名称
Func键< MyObject来,对象> ; FUNC = X => x.DoSomeMethod();
字符串名称= ExtractMethodName(FUNC); //应该等于DoSomeMethod
我怎样才能做到这一点?
- 吹牛的权利 -
请 ExtractMethodName
还与一个属性调用工作,有它在该实例返回属性的名称。
如:
Func键< MyObject来,对象> FUNC = X => x.Property;
字符串名称= ExtractMethodName(FUNC); //应该等于属性
解决方案
看马!无表达式树!
下面是从底层为λ的IL流抓起元数据标记,并解决它快速,肮脏和具体实施的版本。
私有静态字符串ExtractMethodName(Func键< MyObject来,对象> FUNC)
{
变种IL = func.Method.GetMethodBody ().GetILAsByteArray();
//第一个字节是ldarg.0
//第二个字节是callvirt
//接下来的四个字节是MethodDef令牌
VAR mdToken =(IL [5 << 24)| (IL [4]&下;&下; 16)| (IL [3]所述;&下; 8)| IL [2];
VAR innerMethod = func.Method.Module.ResolveMethod(mdToken);
//检查,看看这是一个属性getter和抢财产,如果它是...
如果(innerMethod.IsSpecialName&安培;&安培; innerMethod.Name.StartsWith(的get_ ))
{
VAR道具=(从innerMethod.DeclaringType.GetProperties p()
,其中p.GetGetMethod()== innerMethod
选择p).FirstOrDefault();
如果(丙!= NULL)
返回prop.Name;
}
返回innerMethod.Name;
}
I would like to get the name of the method that is being delegated as a Func.
Func<MyObject, object> func = x => x.DoSomeMethod();
string name = ExtractMethodName(func); // should equal "DoSomeMethod"
How can I achieve this?
-- For bragging rights --
Make ExtractMethodName
also work with a property invocation, having it return the property name in that instance.
eg.
Func<MyObject, object> func = x => x.Property;
string name = ExtractMethodName(func); // should equal "Property"
解决方案
Look Ma! No expression trees!
Here's a quick, dirty and implementation-specific version that grabs the metadata token from the IL stream of the underlying lambda and resolves it.
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;
}
这篇关于检索在函数求执行被调用的方法的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文