下面我有一个解决方案,用扩展方法从字段中获取属性.现在我想用方法而不是字段做类似的事情.
public static MemberInfo GetMember(this T instance, Expression > selector) { var member = selector.Body as MemberExpression; return member?.Member; } public static T GetAttribute (this MemberInfo meminfo) where T : Attribute { return meminfo.GetCustomAttributes(typeof(T)).FirstOrDefault() as T; }
用法:
var attr = this.GetMember(x => x.AddButtonVisibility).GetAttribute();
所以在我的情况下,用法应该是这样的:
var attr = this.GetMethod(x => x.SomeMethod).GetAttribute();
这有可能以任何方式或我必须尝试完全不同的东西吗?
您可以执行以下操作:
public static MethodInfo GetMethod(this T instance, Expression > selector) { var member = selector.Body as MethodCallExpression; return member?.Method; } public static MethodInfo GetMethod (this T instance, Expression > selector) { var member = selector.Body as MethodCallExpression; return member?.Method; }
请注意,您需要以void
不同方式处理方法,因为Func
没有意义,您需要重载Action
.