c# - 自定义属性对抽象属性的继承

标签 c# reflection attributes abstract-class

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

覆盖基础属性(抽象或虚拟)是否会破坏放置在原始属性上的属性?

来自属性类定义

[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
        }

最佳答案

您必须调用静态方法 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);

关于c# - 自定义属性对抽象属性的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2520035/

相关文章:

c# - 在不丢失格式的情况下将 HTML 导出到 Excel

java - 在 driver=new ChromeDriver(); 行上获取 "InvocationTargetException"异常;

ruby-on-rails-3 - 管理员权限的复选框 bool 值

c# - 是否支持导航属性的继承?

c# - 我如何强命名非托管 C++ Dll?

c# - 如何在 .NET 中呈现与浏览器为文本提供 CSS 时相同的大小的文本

java - this.getClass().getFields().length;总是返回 0

reflection - 不使用 RCW 调用 COM 对象方法的最快方法

javascript - 如何用javascript修改html标签?

visual-studio - Visual Studio 中有什么方法可以在抛出特定异常时不中断?