通过linq表达式从重写属性获取属性

时间:2012-04-25 22:40:22

标签: .net linq-expressions getcustomattributes

我正在尝试使用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类。因此,当我获得属性时,它什么都不返回。

1 个答案:

答案 0 :(得分:4)

它无效,因为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));