获取重写的属性属性

时间:2013-12-30 07:20:35

标签: c# inheritance override custom-attributes system.reflection

我有这样的自定义属性:

public class PropertyInfoAttribute : Attribute
{
    public bool IsAutoComplete { get; set; }
}

还有一个这样的课程:

public class Article
{
    public virtual int Order { get; set; }
    //other properties
}

在另一个继承自Article的类中,我重写了Order属性并为它声明了这个属性:

public class ArticleDetails : Article
{
    [PropertyInfo(IsAutoCompele = true)]
    public override int Order { get; set; }
}

当我想通过使用PropertyInfo类中的GetCustomAttributes方法获取属性时,会出现问题。我是这样做的:

PropertyInfo propInfo = //do something for getting property info from the
                        //ArticleDetails class;

var attr = propInfo.GetCustomAttribute<PropertyInfoAttribute>();

但它什么都没有回报!我不知道为什么!

更新

我在这个方法中获得了属性信息:

    public static void InitPropertyInfoAttribute<TModel, TProperty>(MvcHtmlString source, Expression<Func<TModel, TProperty>> expression)
    {
        PropertyInfo propInfo = (expression.Body as MemberExpression).Member as PropertyInfo;
    }

2 个答案:

答案 0 :(得分:1)

我认为问题隐藏在这里:

PropertyInfo propInfo = //do something for getting property info from the
                        //ArticleDetails class;

我假设您实际从Article类获取此属性信息,而不是ArticleDetails,这就是它返回null的原因。以下代码片段对我有效:

PropertyInfo propInfo = typeof(ArticleDetails).GetProperty("Order");
var attr = propInfo.GetCustomAttribute<PropertyInfoAttribute>();

<强>更新


根据您的更新 - 问题是Member的{​​{1}}属性指向MemberExpression类型;

作为解决方案,您可以按如下方式更新Article

InitPropertyInforAttribute

不要忘记,您应该将MemberExpression memberExpression = (expression.Body as MemberExpression); return typeof(TModel).GetProperty(memberExpression.Member.Name); 作为第一个通用类型参数传递 - ArticleDetails

答案 1 :(得分:1)

抱歉,我无法重现错误。提取属性。你能提供详情吗?

// Your classes
public class PropertyInfoAttribute: Attribute {
  public bool IsAutoComplete {
    get;
    set;
  }
}

public class Article {
  public virtual int Order {
    get;
    set;
  }
}

public class ArticleDetails: Article {
  [PropertyInfo(IsAutoComplete = true)]
  public override int Order {
    get;
    set;
  }
}

...

// My test

// Let's do it explicitly:
// ask for public and instance (not static) property
PropertyInfo pi = typeof(ArticleDetails).GetProperty("Order", BindingFlags.Public | BindingFlags.Instance);
// Then ask for the attribute
Attribute at = pi.GetCustomAttribute(typeof(PropertyInfoAttribute));

// And, finally, check if attribute is existing
// ... And so, assertion passes - attribute is existing
Trace.Assert(!Object.ReferenceEquals(null, at), "No Attribute found.");