CKTIS / C#
Attributi delle proprietà: AttributeUsage e selezione con BindingFlags
Dichiara dove è ammesso un attributo, seleziona le proprietà pubbliche di istanza e distingui gli attributi applicati direttamente da quelli ereditati.
Versione: C# 12 and .NET 8; later runtimes may add compatible features
Sintassi
using System;
using System.Reflection;
// Model is the type to inspect.
PropertyInfo[] properties = typeof(Model).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
LabelAttribute? label = property.GetCustomAttribute<LabelAttribute>(inherit: false);
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
sealed class LabelAttribute : Attribute { }[AttributeUsage(...)] è la forma abbreviata di System.AttributeUsageAttribute su una classe di attributo derivata da System.Attribute. AttributeTargets.Property consente di applicare l’attributo a una proprietà indipendentemente dalla sua visibilità e dal fatto che sia statica. Non ha come destinazione né una funzione di accesso né il campo sottostante. ValidOn indica le destinazioni ammesse. AllowMultiple (false per impostazione predefinita) stabilisce se l’attributo può comparire più volte nella stessa dichiarazione; Inherited (predefinito true) stabilisce se può essere ereditato da una proprietà che ne esegue l’override.
Type.GetProperties(BindingFlags.Public | BindingFlags.Instance) usa flag di System.Reflection e restituisce un PropertyInfo[], non i valori delle proprietà. Per la reflection, una proprietà è pubblica se almeno una funzione di accesso è pubblica. | è l’OR bit per bit: l’overload con i flag richiede almeno un flag tra Public e NonPublic e almeno uno tra Instance e Static. Aggiungere DeclaredOnly esclude dall’elenco le proprietà ereditate, ma non controlla la successiva ricerca degli attributi.
property.GetCustomAttribute<T>(inherit: ...) è un metodo di estensione di System.Reflection.CustomAttributeExtensions per MemberInfo, la classe base di PropertyInfo; non è un metodo di istanza di PropertyInfo. T deve derivare da Attribute. La controparte non generica è il metodo statico Attribute.GetCustomAttribute(property, typeof(T), inherit). inherit: false esamina solo quella proprietà; true risale anche la catena degli override se l’attributo è ereditabile. Il metodo di istanza MemberInfo.GetCustomAttributes(..., inherit) ignora inherit per le proprietà.
Se non ci sono corrispondenze, il risultato è null; se ce n’è più di una, viene generata AmbiguousMatchException. Se ti aspetti più corrispondenze, usa l’estensione GetCustomAttributes<T>(inherit: ...). Recuperare un’istanza dell’attributo può eseguirne il costruttore. Per leggere gli argomenti registrati senza creare l’istanza, usa CustomAttributeData, che non cerca gli attributi ereditati.
Esempi
#nullable enable
using System;
using System.Linq;
using System.Reflection;
var usage = typeof(LabelAttribute).GetCustomAttribute<AttributeUsageAttribute>(inherit: false)
?? throw new InvalidOperationException("Missing attribute usage metadata.");
Console.WriteLine($"Usage: {usage.ValidOn}, AllowMultiple={usage.AllowMultiple}, Inherited={usage.Inherited}");
foreach (PropertyInfo property in typeof(Item)
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.OrderBy(p => p.Name, StringComparer.Ordinal))
{
var direct = property.GetCustomAttribute<LabelAttribute>(inherit: false);
var withInheritance = property.GetCustomAttribute<LabelAttribute>(inherit: true);
Console.WriteLine($"{property.Name}: direct={direct?.Text ?? "-"}; with inheritance={withInheritance?.Text ?? "-"}");
}
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
sealed class LabelAttribute : Attribute
{
public LabelAttribute(string text) => Text = text;
public string Text { get; }
}
class BaseItem
{
[Label("base")]
public virtual string Name => "";
}
sealed class Item : BaseItem
{
public override string Name => "";
public string Code { get; private set; } = "";
[Label("private")]
private string Hidden => "";
[Label("static")]
public static string Kind => "";
}Risultato
Usage: Property, AllowMultiple=False, Inherited=True Code: direct=-; with inheritance=- Name: direct=-; with inheritance=base
Il programma legge prima le regole d’uso di `LabelAttribute`, poi stampa le proprietà in ordine ordinale per nome. `Code` non ha un’etichetta e l’override di `Name` trova `base` solo con `inherit: true`. Le proprietà contrassegnate `Hidden` e `Kind` non superano il filtro.
Lezioni correlate
- C# · Lezione 24 · Avanzato · Versione: 3
Fonti
- AttributeUsageAttribute Class (System)
- AttributeTargets Enum (System)
- Attributes - C# language specification
- BindingFlags Enum (System.Reflection)
- Type.GetProperties Method (System)
- CustomAttributeExtensions.GetCustomAttribute Method (System.Reflection)
- CustomAttributeExtensions.GetCustomAttributes Method (System.Reflection)
- Attribute.GetCustomAttribute Method (System)
- MemberInfo.GetCustomAttributes Method (System.Reflection)
- CustomAttributeData Class (System.Reflection)