Binding method names declaratively?

73 views Asked by At

Finding the need to be able to get method names in a declarative manner (for AOP, reflection, etc) such that compiler checking enforces breaking changes etc. Good example:

invocation.Method.Name.Equals("GetAll"

.. is there a way to do this like with a lambda/generic method so i don't have to put the method name as a string literal? I've used things like this before to get property names:

    public static string GetPropertyName<T, P>(Expression<Func<T, P>> propSelector)
        where T : class
    {
        return (propSelector.Body as MemberExpression).Member.Name;
    }

.. but is there a reliable and easy way to do the same for methods?

1

There are 1 answers

0
thecoop On

You can do something like this with delegates:

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

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

If there's a particular delegate signature you use, you can create specific overloads:

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

MethodName(Convert.ToInt32);

You might also be able to do something with generics, if you have a play around with it.