asp net 3.5unleashed

Page 316

When defining an attribute type’s instance constructor, fields, and properties, you must restrict yourself to a small subset of data types. Specifically, the legal set of data types is limited to any of the following: Boolean, Char, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, String, Type, Ob-ject, or an enumerated type. In addition, you can use a single-dimension, zero-based array of any of these types. When applying an attribute, you must pass a compile-time constant expression that matches the type defined by the attribute class. Wherever the attribute class defines a Type parameter, Type field, or Type property, you must use C#’s typeof operator as shown in the following code. Wherever the attribute class defines an Object parameter, Object field, or Object property, you can pass an Int32, a String, or any other constant expression. If the constant expression represents a value type, the value type will be boxed at run time when an instance of the attribute is constructed. Here’s an example of an attribute and an application of it: [AttributeUsage(AttributeTargets.All)] class SomeAttribute : Attribute { public SomeAttribute(String name, Object o, Type[] types) { // ‘name’ // ‘o’ necessary).

refers to a String. refers to one of the legal types (boxing if

// ‘types’ refers to a 1-dimension, 0-based array of Types. ? } }

[Some("Jeff", Color.Red, new Type[] { typeof(Math), typeof(Console) })] public class SomeType { ... } Logically, when a compiler detects a custom attribute applied to a target, the compiler constructs an instance of the attribute type by calling its constructor, passing it any specified parameters. Then the compiler initializes any public fields and properties that have also been specified. Now that the custom attribute object is initialized, the compiler serializes the object out to the target’s metadata table entry. Important I’ve found that this is the best way for developers to think of custom attributes: instances of types that have been serialized to a byte stream that resides in metadata. Later, at run time, an instance of the type can be constructed by deserializing the bytes contained in the metadata. Note Each parameter is written out with a 1-byte type ID followed by the value. After “serializing” the constructor’s parameters, the compiler emits each of the specified field and property values by writing out the field/property name followed by a 1-byte type ID and then the value. For arrays, the count of elements is saved first, followed by each individual element.


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.