【问题标题】:Getting attribute from overridden property via a linq Expression通过 linq 表达式从被覆盖的属性中获取属性
【发布时间】:2017-01-22 23:10:26
【问题描述】:

我正在尝试使用GetCustomAttributes() 来获取在属性上定义的属性。问题是该属性是一个被覆盖的属性,我无法弄清楚如何从表达式中提取被覆盖的属性。我只能弄清楚如何获得基类的那个。

这里有一些代码

public class MyAttribute : Attribute 
{
  //... 
}

public abstract class Text
{
  public abstract string Content {get; set;}
}

public class Abstract : Text
{
  [MyAttribute("Some Info")]
  public override string Content {get; set;}
}

现在我正试图将MyAttribute 从抽象类中取出。但我需要通过Expression 获得它。这是我一直在使用的:

Expression<Func<Abstract, string>> expression =  c => c.Content;
Expression exp = expression.Body;
MemberInfo memberType = (exp as MemberExpression).Member;

var attrs = Attribute.GetCustomAttributes(memberType, true);

不幸的是,atts 最终是空的。问题是 menberType 最终是 Text.Content 而不是 Abstract.Content 类。所以当我得到属性时,它什么也不返回。

【问题讨论】:

    标签: .net linq-expressions getcustomattributes


    【解决方案1】:

    它不起作用,因为 MemberExpression 忽略覆盖并从基本类型 Text 返回属性,这就是您找不到属性的原因。

    您可以在此处阅读有关此问题的信息:How to get the child declaring type from an expression?

    但是,您拥有表达式中的所有信息,并且您可以通过更多反射(快速而肮脏的示例)获得您的属性:

    Expression<Func<Abstract, string>> expression = (Abstract c) => c.Content;
    Expression exp = expression.Body;
    MemberInfo memberType = (exp as MemberExpression).Member;
    
    var attrs = Attribute.GetCustomAttributes(
    expression.Parameters[0].Type.GetProperty(memberType.Name));
    

    【讨论】:

    • 感谢其他问题的链接。我搜索了类似的东西,但没有找到。
    • 您提供的解决方案是我迄今为止一直在使用的解决方案,很高兴获得对该解决方案的一些独立支持 :-) 谢谢
    猜你喜欢
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 2017-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多