Binding method names declaratively?
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>> prop开发者_运维知识库Selector)
where T : class
{
return (propSelector.Body as MemberExpression).Member.Name;
}
.. but is there a reliable and easy way to do the same for methods?
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.
精彩评论