下面我有一个解决方案,用扩展方法从字段中获取属性.现在我想用方法而不是字段做类似的事情.
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>();
这有可能以任何方式或我必须尝试完全不同的东西吗?
解决方法
您可以执行以下操作:
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>> selector) { var member = selector.Body as MethodCallExpression; return member?.Method; }
请注意,您需要以不同方式处理void方法,因为Func< T,R>没有意义,你需要一个Action< T>重载.