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

ber*_*rko 2 c# lambda delegates methodinfo

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

Func<MyObject, object> func = x => x.DoSomeMethod();
string name = ExtractMethodName(func); // should equal "DoSomeMethod"
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

- 吹牛的权利 -

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

例如.

Func<MyObject, object> func = x => x.Property;
string name = ExtractMethodName(func); // should equal "Property"
Run Code Online (Sandbox Code Playgroud)

Dus*_*ell 11

看马!没有表达树!

这是一个快速,脏和特定于实现的版本,它从底层lambda的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;
}
Run Code Online (Sandbox Code Playgroud)