< Day Day Up > |
TechniqueYou 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. CommentsThe 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 > |