< Day Day Up > |
TechniqueThe technique is to apply a Microsoft-defined attribute, AttributeUsageAttribute , to your attribute class. For example, suppose you wrote a custom attribute, InHouseAttribute (as defined in Recipe 25.1, "Creating a Custom Attribute Class Definition"), and you want to explicitly indicate that it can be applied only to classes. Listing 25.6 shows how you achieve this goal. Listing 25.6 Indicating an Attribute Can Only Be Applied to Classes[AttributeUsage(AttributeTargets.Class)] public class InHouseAttribute : Attribute { // etc. Of course, you might want an attribute to be applied to any struct, class, or enum, rather than only to classes, as in Listing 25.7. Listing 25.7 Indicating an Attribute Can Be Applied to Classes, Structs, or Enums[AttributeUsage(AttributeTargets.Class AttributeTargets.Struct AttributeClass.Enum)] public class InHouseAttribute : Attribute { // etc. In general, any attempt to apply an attribute to an item of code that the AttributeTarget forbids will result in a compilation error. As you might guess, AttributeTargets is a [Flags] enum. (These attributes pop up everywhere!) The full set of possible values of this enumeration follows : All Enum Module Assembly Event Parameter Class Field Property Constructor Interface ReturnValue Delegate Method Struct The meanings of these values should be self-explanatory. You can combine any of these individual values with a bitwise OR operation. AttributeTargets.All is itself a bitwise OR of all the other values. Hence, marking an attribute with AttributeTargets.All allows its use anywhere . This behavior is the default if you do not specify AttributeUsage . Note the following code: [AttributeUsage(AttributeTargets.All)] public class InHouseAttribute : Attribute { // etc. It has much the same practical effect as the next code: public class InHouseAttribute : Attribute { // etc. On occasions, you might want to allow an attribute to be applied everywhere except certain places. For example, you might want an attribute to be permissible on any items of source code but not to assemblies or modules. Achieving this goal takes some playing around with logical operations; the correct procedure is to perform a logical AND of AttributeTargets.All with the bitwise negation of the attributes you don't want. Listing 25.8 uses this procedure to prevent an attribute from being applied to an assembly or module. Listing 25.8 Defining an Attribute That Cannot Be Applied at Assembly or Module Scope[AttributeUsage(AttributeTargets.All & (~AttributeTargets.Assembly) & (~AttributeTargets .Module))] public class MyAttribute : Attribute { // etc. |
< Day Day Up > |