Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
737 views
in Technique[技术] by (71.8m points)

c# - Inheritance of Custom Attributes on Abstract Properties

I've got a custom attribute that I want to apply to my base abstract class so that I can skip elements that don't need to be viewed by the user when displaying the item in HTML. It seems that the properties overriding the base class are not inheriting the attributes.

Does overriding base properties (abstract or virtual) blow away attributes placed on the original property?

From Attribute class Defination

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

From Abstract Class Defination

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

From Concrete Class Defination

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

From class checking for attribute

        Type t = o.GetType();
        foreach (PropertyInfo pi in t.GetProperties())
        {
            if (pi.GetCustomAttributes(typeof(NoHtmlOutput), true).Length == 1)
                continue;
            // processing logic goes here
        }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Instead of calling PropertyInfo.GetCustomAttributes(...), you have to call the static method System.Attribute.GetCustomAttributes(pi,...), as in:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...