Attribute
Apparence
Héritage
Les classes héritent des attributs de leurs classes parentes mais pas de leurs interfaces.
Création d'un attribut
// classe publique
// cet attribut s'applique aux propriétés
// AllowMultiple: l'attribut peut être déclaré plusieurs fois
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class MyAttribute : Attribute
{
// au moins un constructeur publique
public MyAttribute(string positionalParameter)
{
PositionalParameter = positionalParameter;
}
// positional parameter: argument du constructeur
public readonly string PositionalParameter;
// named parameter: optionnel
public string NamedParameter { get; private set; }
}
// utilisation
class MaClasse
{
[My("paramètre")] // PositionalParameter = "paramètre"
public string MaPropriété { get; set; }
}
|
![]() |
By convention, all attribute names end with the word "Attribute" |
Cible: AttributeTargets
Définit à quelle entité s'applique l'attribut
[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class MyAttribute : Attribute
{}
|
- All
- Class
- Method
- Property
Types de paramètres autorisés
Pas de types custom et pas de délégués.
Accéder aux attributs par réflexion
// récupérer un type d'attribut sur une classe
var myAttribute = (MyAttribute)Attribute.GetCustomAttribute(typeof(MyClass), typeof(MyAttribute), false);
// récupérer tous les attributs d'un type sur une classe
var myAttributes = (MyAttribute[])Attribute.GetCustomAttributes(typeof(MyClass), typeof(MyAttribute), false);
// récupérer un type d'attribut sur une propriété
var myAttribute = (MyAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(MyAttribute), false);
|