25.4 Defining the Inheritance Model of Custom Attributes

 <  Day Day Up  >  

You want to specify whether items decorated with some custom attribute can pass the attribute on to inherited items.


Technique

You can control whether decorated items can pass attributes on to derived items with the AttributeUsage.Inherited property. By default, this property is set to true , meaning that attributes are passed on to inherited items. For example, let's take the InHouseAttribute class presented in Listing 25.1:

 
 public class InHouseAttribute : Attribute { } 

Let us assume that it is applied as follows :

 
 [InHouse()] class OurClass {         // etc. 

Suppose also that we have a class defined as follows:

 
 class OurDerivedClass : OurClass {         // etc. 

Then, OurDerivedClass also has the InHouse attribute applied to it, despite the fact that it is not explicitly indicated as such: it will have inherited the attribute from OurClass . To change this behavior, we must specifically indicate the attribute usage of InHouse and mark its Inherited property as false . Listing 25.11 shows this process.

Listing 25.11 Defining an Attribute That Cannot Be Passed on to Inherited Items
 [AttributeUsage(AttributeTargets.All, Inherited=false)] public class InHouseAttribute : Attribute { } 

Now, with OurDerivedClass still defined as in Listing 25.11, OurDerivedClass will not be decorated with the InHouse attribute.

Comments

The examples shown here illustrate an attribute that has been defined to a type. However, the same principles apply to any item that can be overridden or inherited from. It includes classes, methods , or properties. For example, suppose the class OurClass is defined like this:

 
 class OurClass {        [InHouse()]        public virtual void DoSomething()        {                        // etc. 

Suppose OurDerivedClass contained this method:

 
 class OurDerivedClass {         public override void DoSomething()         {                         // etc. 

By default, the overridden method OurDerivedClass.DoSomething() will be marked with the InHouse attribute; it will have picked up this attribute with the base class method. However, if InHouseAttribute is marked as Inherited=false , then OurDerivedClass.DoSomething() does not gain this attribute unless explicitly coded.

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net