CKTIS / C#
Atributi lastnosti: AttributeUsage in izbor z BindingFlags
Določi, kje je atribut dovoljen, izberi javne lastnosti primerka ter loči neposredno uporabljene atribute od podedovanih.
Različica: C# 12 and .NET 8; later runtimes may add compatible features
Sintaksa
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(...)] je krajši zapis za System.AttributeUsageAttribute na razredu atributa, izpeljanem iz System.Attribute. AttributeTargets.Property dovoljuje uporabo atributa na lastnosti ne glede na njeno vidnost ali na to, ali je statična. Cilj ni dostopna metoda ali podporno polje. ValidOn navede dovoljene cilje. AllowMultiple (privzeto false) določa, ali se atribut lahko ponovi na isti deklaraciji; Inherited (privzeto true) določa, ali ga lahko podeduje lastnost, ki prepiše drugo lastnost.
Type.GetProperties(BindingFlags.Public | BindingFlags.Instance) uporablja zastavice iz System.Reflection in vrne tabelo PropertyInfo[], ne vrednosti lastnosti. Za refleksijo je lastnost javna, če je javna vsaj ena njena dostopna metoda. | je bitni ALI: preobremenitev z zastavicami zahteva vsaj eno zastavico iz para Public/NonPublic in eno iz para Instance/Static. Če dodaš DeclaredOnly, bodo podedovane lastnosti izključene s seznama, to pa ne vpliva na poznejše iskanje atributov.
property.GetCustomAttribute<T>(inherit: ...) je razširitvena metoda iz System.Reflection.CustomAttributeExtensions za MemberInfo, osnovni razred razreda PropertyInfo; ni metoda primerka razreda PropertyInfo. T mora biti izpeljan iz Attribute. Negenerična ustreznica je statična metoda Attribute.GetCustomAttribute(property, typeof(T), inherit). inherit: false preveri samo navedeno lastnost; true preišče tudi verigo prepisanih lastnosti, če se atribut lahko deduje. Metoda primerka MemberInfo.GetCustomAttributes(..., inherit) pri lastnostih prezre inherit.
Če ni zadetka, je rezultat null; več zadetkov sproži AmbiguousMatchException. Če pričakuješ več zadetkov, uporabi razširitev GetCustomAttributes<T>(inherit: ...). Pri pridobivanju primerka atributa se lahko izvede njegov konstruktor. Za pregled shranjenih argumentov brez ustvarjanja primerka uporabi CustomAttributeData, ki ne išče podedovanih atributov.
Primeri
#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 => "";
}Rezultat
Usage: Property, AllowMultiple=False, Inherited=True Code: direct=-; with inheritance=- Name: direct=-; with inheritance=base
Program najprej prebere pravila uporabe za `LabelAttribute`, nato pa lastnosti izpiše v ordinalnem vrstnem redu po imenu. `Code` nima oznake, prepisana lastnost `Name` pa najde `base` le z `inherit: true`. Označeni lastnosti `Hidden` in `Kind` ne prestaneta filtra.
Povezane lekcije
- C# · Lekcija 24 · Napredna · Različica: 3
Viri
- 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)