自定义属性在抽象属性上的继承

Mar*_*uth 45 c# reflection attributes abstract-class

我有一个自定义属性,我想应用于我的基本抽象类,以便我可以跳过在HTML中显示项目时用户不需要查看的元素.似乎覆盖基类的属性不继承属性.

重写基本属性(抽象或虚拟)是否会破坏原始属性上的属性?

从属性类定义

[AttributeUsage(AttributeTargets.Property,
                Inherited = true,
                AllowMultiple = false)]
public class NoHtmlOutput : Attribute
{
}
Run Code Online (Sandbox Code Playgroud)

从抽象类定义

[NoHtmlOutput]
public abstract Guid UniqueID { get; set; }
Run Code Online (Sandbox Code Playgroud)

从混凝土类定义

public override Guid UniqueID{ get{ return MasterId;} set{MasterId = value;}}
Run Code Online (Sandbox Code Playgroud)

从类检查属性

        Type t = o.GetType();
        foreach (PropertyInfo pi in t.GetProperties())
        {
            if (pi.GetCustomAttributes(typeof(NoHtmlOutput), true).Length == 1)
                continue;
            // processing logic goes here
        }
Run Code Online (Sandbox Code Playgroud)

Joh*_*day 61

您必须调用静态方法System.Attribute.GetCustomAttributes(pi,...),而不是调用PropertyInfo.GetCustomAttributes(...),如下所示:

PropertyInfo info = GetType().GetProperties();

// this gets only the attributes in the derived class and ignores the 'true' parameter
object[] DerivedAttributes = info.GetCustomAttributes(typeof(MyAttribute),true);

// this gets all of the attributes up the heirarchy
object[] InheritedAttributes = System.Attribute.GetCustomAttributes(info,typeof(MyAttribute),true);
Run Code Online (Sandbox Code Playgroud)

  • 在.NET 4.6.1中对我不起作用.尝试从Entity Framework动态代理(其基类型为POCO类)的POCO类中获取属性. (4认同)
  • 这应该是答案。从 `mytype.GetCustomAttributes()` 更改为 `System.Attribute.GetCustomAttribute()` 会使 `inherit` 参数按预期工作。魔法! (2认同)

wom*_*omp 30

不,属性是继承的.

GetCustomAttributes()是不查看父声明的方法.它仅查看应用于指定成员的属性. 来自文档:

备注

此方法忽略属性和事件的inherit参数.要在继承链中搜索属性和事件的属性,请使用Attribute .. ::.GetCustomAttributes方法的相应重载.

  • imo,这是一个奇怪的bug,奇怪的是它甚至在.NET 4.5中都没有修复.那为什么要提供bool超载呢! (6认同)
  • 有人得到Eric Lippert的电话,并弄清楚为什么这仍然是一个问题. (3认同)
  • 没关系....微软必须把它放在可能的最小型面上 (2认同)