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?
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With