Reflection 以声明方式绑定方法名?

Reflection 以声明方式绑定方法名?,reflection,binding,methods,lambda,declarative,Reflection,Binding,Methods,Lambda,Declarative,发现需要能够以声明的方式获取方法名(对于AOP、反射等),以便编译器检查强制执行破坏性更改等。很好的示例: invocation.Method.Name.Equals("GetAll" 。。有没有一种方法可以像使用lambda/generic方法那样做到这一点,这样我就不必将方法名作为字符串文字? 我以前使用过类似的方法来获取属性名称: public static string GetPropertyName<T, P>(Expression<Func<T, P

发现需要能够以声明的方式获取方法名(对于AOP、反射等),以便编译器检查强制执行破坏性更改等。很好的示例:

invocation.Method.Name.Equals("GetAll"
。。有没有一种方法可以像使用lambda/generic方法那样做到这一点,这样我就不必将方法名作为字符串文字? 我以前使用过类似的方法来获取属性名称:

    public static string GetPropertyName<T, P>(Expression<Func<T, P>> propSelector)
        where T : class
    {
        return (propSelector.Body as MemberExpression).Member.Name;
    }
公共静态字符串GetPropertyName(表达式propSelector)
T:在哪里上课
{
返回(propSelector.Body作为MemberExpression).Member.Name;
}

。。但是,有没有一种可靠且简单的方法可以对方法执行相同的操作?

您可以对代理执行以下操作:

public static string MethodName(Delegate d) {
    return d.Method.Name;
}

// and to use...
MethodName(new Func<object, int>(Convert.ToInt32));
公共静态字符串方法名(委托d){
返回d.Method.Name;
}
//使用。。。
方法名(新函数(Convert.ToInt32));
如果使用特定的委托签名,则可以创建特定的重载:

public static string MethodName(Func<object, int> d) {
    return MethodName((Delegate)d);
}

MethodName(Convert.ToInt32);
公共静态字符串方法名(Func d){
返回MethodName((委托)d);
}
方法名(转换为32);

如果您有机会使用泛型,您也可以使用泛型进行操作。

您可以使用代理执行类似操作:

public static string MethodName(Delegate d) {
    return d.Method.Name;
}

// and to use...
MethodName(new Func<object, int>(Convert.ToInt32));
公共静态字符串方法名(委托d){
返回d.Method.Name;
}
//使用。。。
方法名(新函数(Convert.ToInt32));
如果使用特定的委托签名,则可以创建特定的重载:

public static string MethodName(Func<object, int> d) {
    return MethodName((Delegate)d);
}

MethodName(Convert.ToInt32);
公共静态字符串方法名(Func d){
返回MethodName((委托)d);
}
方法名(转换为32);
如果您有机会使用泛型,您也可以使用泛型做一些事情