【问题标题】:Accessing attributes on methods using extension method使用扩展方法访问方法的属性
【发布时间】:2017-01-23 13:37:29
【问题描述】:

下面我有一个使用扩展方法从字段中获取属性的解决方案。现在我想用方法而不是字段来做类似的事情。

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 上面的代码无效,但我想用方法而不是字段来做同样的事情。

标签: c# linq extension-methods custom-attributes


【解决方案1】:

您可以执行以下操作:

 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&lt;T, R&gt; 没有意义,您需要使用 Action&lt;T&gt; 进行重载。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多