自定义属性对抽象属性的inheritance

我有一个自定义属性,我想要应用到我的基本抽象类,以便我可以跳过HTML中显示项目时用户不需要查看的元素。 看来覆盖基类的属性不会inheritance属性。

重写基本属性(抽象还是虚拟)会吹走放置在原始属性上的属性?

从属性类定义

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

从抽象类定义

 [NoHtmlOutput] public abstract Guid UniqueID { get; set; } 

从具体类的定义看

 public override Guid UniqueID{ get{ return MasterId;} set{MasterId = value;}} 

从类检查属性

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

不,属性是inheritance的。

这是GetCustomAttributes()方法,不查看父声明。 它只查看应用于指定成员的属性。 从文档 :

备注

此方法忽略属性和事件的inheritance参数 。 要在inheritance链中search属性和事件的属性,请使用Attribute .. ::。GetCustomAttributes方法的相应重载。

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

 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); 

看起来只有当重写的方法也具有该属性时才会发生。

http://msdn.microsoft.com/en-us/library/a19191fh.aspx

但是,您可以覆盖相同types的属性或将其他属性应用于派生组件。 以下代码片段显示了一个自定义控件,该控件通过覆盖基类中应用的BrowsableAttribute属性来覆盖从Controlinheritance的Text属性。 Visual Basic

 Public Class MyControl Inherits Control ' The base class has [Browsable(true)] applied to the Text property. <Browsable(False)> _ Public Overrides Property [Text]() As String ... End Property ... End Class 

这是我的尝试。 这是MemberInfo上的一个扩展方法, MemberInfo手动MemberInfoinheritance层次结构。 这似乎是与dynamic代理兼容…至less软pipe由城堡创build,所以我假设它将与任何代理库兼容。

 public static IEnumerable<T> GetCustomAttributes<T>(this MemberInfo instance) { while (instance != null) { object[] attributes = instance.GetCustomAttributes(typeof(T), false); if (attributes.Length > 0) { return attributes.Cast<T>(); } Type ancestor = instance.DeclaringType.BaseType; if (ancestor != null) { IEnumerable<MemberInfo> ancestormatches = ancestor.FindMembers(instance.MemberType, BindingFlags.Instance | BindingFlags.Public, (m, s) => { return m.Name == (string)s; }, instance.Name); instance = ancestormatches.FirstOrDefault(); } else { instance = null; } } return new T[] { }; } 

你会这样使用它。

 Type t = o.GetType(); foreach (PropertyInfo pi in t.GetProperties()) { IEnumerable<NoHtmlOutput> attributes = pi.GetCustomAttributes<NoHtmlOutput>(); foreach (NoHtmlOutput attribute in attributes) { Console.WriteLine(attribute); } } 

您可以使用

 PropertyInfo::GetCustomAttributes<T>(true) 

哪些工作正常,请参阅示例: https : //dotnetfiddle.net/2IhEWH

所以,没有必要使用静态方法

 System.Attribute.GetCustomAttributes