使用扩展方法访问方法上的属性

7

下面是使用扩展方法从字段中获取属性的解决方案。现在我想用类似的方式来处理方法,而不是字段。

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;
}

使用方法:

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

所以在我的情况下,使用应该像这样:

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

有没有任何办法可以实现这个,或者我必须尝试完全不同的东西?

你有收到任何错误吗?你的问题不太清楚。同样的情况也适用于MethodInfo。 - Nkosi
@Nkosi 不,上面的代码是有效的,但我想用方法来做同样的事情,而不是字段。 - Hans Dabi
1个回答

6
您可以执行以下操作:
 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;
 }

请注意,您需要以不同的方式处理void方法,因为Func<T, R>没有意义,您需要使用重载和Action<T>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接