绑定方法名称是否以声明方式?

时间:2011-02-11 08:55:48

标签: reflection binding methods lambda declarative

发现需要能够以声明方式(对于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;
    }

..但是有一种可靠而简单的方法来为方法做同样的事情吗?

1 个答案:

答案 0 :(得分:0)

你可以用代表做这样的事情:

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

// and to use...
MethodName(new Func<object, int>(Convert.ToInt32));

如果您使用了特定的委托签名,则可以创建特定的重载:

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

MethodName(Convert.ToInt32);

如果你玩弄它,你也可以用泛型做点什么。