Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing attributes on methods using extension method

Below I have a solution to get attributes from fields with an extension method. Now I want to do a similar thing with methods instead of fields.

public static MemberInfo GetMember<T, R>(this T instance, Expression<Func<T, R>> selector)
{
    var member = selector.Body as MemberExpression;
    return member?.Member;
}

public static T GetAttribute<T>(this MemberInfo meminfo) where T : Attribute
{
    return meminfo.GetCustomAttributes(typeof(T)).FirstOrDefault() as T;
}

Usage:

var attr = this.GetMember(x => x.AddButtonVisibility).GetAttribute<Test>(); 

So in my case the usage should look something like this:

var attr = this.GetMethod(x => x.SomeMethod).GetAttribute<Test>();

Is this possible in any way or do I have to try something completely different?

like image 274
Hans Dabi Avatar asked Jan 23 '17 13:01

Hans Dabi


1 Answers

You can do the following:

 public static MethodInfo GetMethod<T>(this T instance, Expression<Action<T>> selector)
 {
     var member = selector.Body as MethodCallExpression;
     return member?.Method;
 }

 public static MethodInfo GetMethod<T, R>(this T instance, Expression<Func<T, R>> selector)
 {
     var member = selector.Body as MethodCallExpression;
     return member?.Method;
 }

Note that you need to handle void methods differently because Func<T, R> makes no sense, you need an overload with Action<T>.

like image 58
InBetween Avatar answered Oct 15 '22 03:10

InBetween