Using Custom Attributes

Custom attributes are placed directly before the source code symbol to which the attribute applies. Attributes can be placed before

  • variables and constants
  • procedures and functions
  • function results
  • procedure and function parameters
  • types
  • fields, properties, and methods

Note that Delphi for .NET supports the use of named properties in the initialization. These can be the names of properties, or of public fields of the custom attribute class. Named properties are listed after all of the parameters required by the constructor. For example

[TCustomCodeAttribute(1024, prop1=512, prop2=128)] TMyClass = class(TObject)

end;

applies the custom attribute declared above to the class TMyClass.

The first parameter, 1024, is the value required by the constructor. The second two parameters are the properties defined in the custom attribute.

When a custom attribute is placed before a list of multiple variable declarations, the attribute applies to all variables declared in that list. For example var

[TCustomAttribute(1024, prop1=512, prop2=128)] x, y, z: Integer;

would result in TCustomAttribute being applied to all three variables, X, y, and z.

Custom attributes applied to types can be detected at runtime with the GetCustomAttributes method of the Type class. The following Delphi code demonstrates how to query for custom attributes at runtime.

F: TMyClass; // TMyClass declared above

T: System.Type;

A: array of TObject; // Will hold custom attributes

I: Integer; begin

A := T.GetCustomAttributes(True);

  • Write the type name, and then loop over custom
  • attributes returned from the call to
  • System.Type.GetCustomAttributes.

Writeln(T.FullName);

Writeln(A[I].GetType.FullName);

end.

Project Management Made Easy

Project Management Made Easy

What you need to know about… Project Management Made Easy! Project management consists of more than just a large building project and can encompass small projects as well. No matter what the size of your project, you need to have some sort of project management. How you manage your project has everything to do with its outcome.

Get My Free Ebook


Post a comment