CodeBlanks Logo Icon CodeBlanks

Attribute okuma

C# kursu · İleri seviye · Ders 51/83

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

  1. Metodu dönüşüne eşle

    GetCustomAttribute
    Tek attribute
    GetCustomAttributes
    Attribute dizisi
    IsDefined
    Var mı?
    AttributeUsage
    Hedef kısıtı
  2. GetCustomAttribute çağrısını tamamla

    var attr = Attribute.____(typeof(Sample), typeof(NoteAttribute));
    Cevabı göster
    var attr = Attribute.GetCustomAttribute(typeof(Sample), typeof(NoteAttribute));
  3. 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.

İleri seviye bölümündeki tüm dersler