Attribute okuma
Reflection ile attribute'ları okumayı öğrenirsin.
Attribute okuma
Attribute'lar reflection ile okunur. Attribute.GetCustomAttribute(member, typeof(MyAttr)) tek bir attribute döndürür; GetCustomAttributes ise bir dizi döndürür. Dönüş değeri object türündendir, gerçek tipe çevrilmelidir.
Bu, attribute'ın yalnızca bildirildiğini değil, aynı zamanda çalışma zamanında erişilebilir olduğunu gösterir. Sağlayıcılar, serileştiriciler ve denetim araçları bu yolla özelleştirilmiş davranışlar uygular.
Türetilmiş sınıflar
GetCustomAttributes(true) miras alınan attribute'ları da döndürür; false yalnızca doğrudan uygulananları. AttributeUsage üzerindeki Inherited özelliği, attribute'ün türetilmiş sınıflara geçip geçmeyeceğini belirler.
Örneğin bir taban sınıfa [Note("Temel")] uygulanmışsa ve Inherited = true ise, türetilmiş sınıftan da bu attribute okunabilir. Inherited = false ise yalnızca doğrudan uygulandığı sınıfta görülür.
Uygulama NoteAttribute oku ve Text yazdır
Aşağıdaki Sample sınıfına [Note("Selam")] uygula. Main içinde Attribute.GetCustomAttribute(typeof(Sample), typeof(NoteAttribute)) as NoteAttribute ile attribute'ı oku ve Console.WriteLine(attr.Text) ile metni yazdır.
Örnek çözümü göster
var attr = Attribute.GetCustomAttribute(typeof(Sample), typeof(NoteAttribute)) as NoteAttribute; Console.WriteLine(attr.Text);
Örnek çözüm:
using System;
[AttributeUsage(AttributeTargets.All)]
public class NoteAttribute : Attribute
{
public string Text { get; set; }
public NoteAttribute(string text) { Text = text; }
}
[Note("Selam")]
class Sample { }
class Program
{
static void Main()
{
var attr = Attribute.GetCustomAttribute(typeof(Sample), typeof(NoteAttribute)) as NoteAttribute;
Console.WriteLine(attr.Text);
}
}
Kendini test et
-
Metodu dönüşüne eşle
- GetCustomAttribute
- Tek attribute
- GetCustomAttributes
- Attribute dizisi
- IsDefined
- Var mı?
- AttributeUsage
- Hedef kısıtı
-
GetCustomAttribute çağrısını tamamla
var attr = Attribute.____(typeof(Sample), typeof(NoteAttribute));Cevabı göster
var attr = Attribute.GetCustomAttribute(typeof(Sample), typeof(NoteAttribute)); -
Attribute.GetCustomAttributes ne döndürür?
- Bir Type nesnesi
- Bir MethodInfo
- Bir bool
- Attribute dizisi
Cevabı göster
Attribute dizisi — Doğru. GetCustomAttributes bir attribute dizisi döndürür.