~~~~~~~~~~~~~~~~~~~~~~~~~
var
Attributes: AttributeCollection;
begin
Attributes := TypeDescriptor.GetAttributes(Self) ;
~~~~~~~~~~~~~~~~~~~~~~~~~
Note that you can pass an instance (such as Self, or this in C#) or a System.Type to TypeDescriptor.GetAttributes(..). It really only works on the Type, since attributes are meta-data on the type, and not the instance.
Once you have the AttributeCollection, you can browse them all with a few lines of code:
~~~~~~~~~~~~~~~~~~~~~~~~~
for AnAttribute in Attributes do
begin
TextBox1.Text := TextBox1.Text + AnAttribute.ToString + #13#10;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~
In addition, if you want a particular attribute, you can directly access it by type:
~~~~~~~~~~~~~~~~~~~~~~~~~
var
Attributes: AttributeCollection;
DefaultEventAttr: DefaultEventAttribute;
begin
...
DefaultEventAttr := DefaultEventAttribute(Attributes[TypeOf(DefaultEventAttribute)]) ;
if DefaultEventAttr <> nil then Text := 'Has a Default Event name of: ' + DefaultEventAttr.Name;
~~~~~~~~~~~~~~~~~~~~~~~~~
Note that it may return null if the Type does not have that attribute applied to it.
If you need Attribute information for a particular member in a type, you can use reflection to find that event, and then use Attribute.GetCustomAttributes(..) to access the attributes that are on that method:
~~~~~~~~~~~~~~~~~~~~~~~~~
[TMyCustomMethodAttriute]
procedure TMainForm.Button1_Click(sender: System.Object; e: System.EventArgs) ;
var
MyType: System.Type;
ClickMethod: MethodInfo;
MethodAttrs: array of Attribute;
MethodAttr: Attribute;
j: Integer;
begin
{ Use reflection to get the Button1_Click member}
MyType := GetType;
ClickMethod := MyType.GetMethod('Button1_Click', BindingFlags.NonPublic or BindingFlags.Instance) ;
MethodAttrs := Attribute.GetCustomAttributes(ClickMethod) ;
TextBox1.Text := '--- Method Attributes --- '#13#10;
for j := 0 to Length(MethodAttrs) - 1 do
begin
MethodAttr := MethodAttrs[j];
TextBox1.Text := TextBox1.Text + MethodAttr.ToString + #13#10;
end;
~~~~~~~~~~~~~~~~~~~~~~~~~
When using Attribute.GetCustomAttributes(...), you can pass a second parameter telling to include attributes declared in ancestor types. In this example, it wouldnt change anything, since the method isnt inherited from an ancestor.
Your Own Attributes
It is very easy to create your own attribute. There are just a few things to keep in mind. First of all, every attribute must directly, or indirectly derive from System.Attribute:
~~~~~~~~~~~~~~~~~~~~~~~~~
{ This can only be applied to methods }
[AttributeUsage(AttributeTargets.Method)]
TMyCustomMethodAttriute = class(Attribute)
...
end;
~~~~~~~~~~~~~~~~~~~~~~~~~
Notice the AttributeUsageAttribute applied to the new custom attribute. This tells compilers where they can allow the attribute to be used.

