GetMethods ve GetProperties
Type üzerinde metot ve özellik listelemeyi öğrenirsin.
GetMethods ve GetProperties
Type.GetMethods() bir tipin public metotlarını MethodInfo[] olarak listeler. Type.GetProperties() ise public özellikleri PropertyInfo[] olarak verir. Her dizi, ilgili üyenin metadata'sını tutar.
Varsayılan olarak yalnızca public üyeler döner. BindingFlags ile özel, statik veya örnek üyeleri de isteyebilirsin. Bu listeler, reflection ile dinamik çağrı ve özellik erişimi için temeldir.
BindingFlags
GetMethods() parametresiz çağrıldığında yalnızca public üyeleri döner. Özel, statik veya miras alınmayan üyeleri görmek için BindingFlags kullanırsın: GetMethods(BindingFlags.NonPublic | BindingFlags.Instance).
Yaygın bayraklar: Public, NonPublic, Instance, Static, DeclaredOnly. DeclaredOnly miras alınan üyeleri elemez. Birden çok bayrak | ile birleştirilir.
Uygulama Bir sınıfın özellik sayısını yazdır
Aşağıdaki Sample sınıfı için Type t = typeof(Sample); ile türünü al. t.GetMethods() ve t.GetProperties() çağrılarını yap. props.Length değerini Console.WriteLine ile yazdır.
Örnek çözümü göster
Type t = typeof(Sample); MethodInfo[] methods = t.GetMethods(); PropertyInfo[] props = t.GetProperties(); Console.WriteLine(props.Length);
Örnek çözüm:
using System;
using System.Reflection;
class Sample
{
public string Name { get; set; }
public int Age { get; set; }
public void Hello() { }
}
class Program
{
static void Main()
{
Type t = typeof(Sample);
MethodInfo[] methods = t.GetMethods();
PropertyInfo[] props = t.GetProperties();
Console.WriteLine(props.Length);
}
}
Kendini test et
-
GetMethods çağrısını tamamla
MethodInfo[] methods = typeof(string).____();Cevabı göster
MethodInfo[] methods = typeof(string).GetMethods(); -
Metodu dönüş türüne eşle
- GetMethods()
- MethodInfo[]
- GetProperties()
- PropertyInfo[]
- GetFields()
- FieldInfo[]
- GetConstructors()
- ConstructorInfo[]
-
GetMethods() varsayılan olarak ne döndürür?
- Tüm metotları (özel dahil)
- Yalnızca static metotları
- Yalnızca void metotları
- Yalnızca public metotları
Cevabı göster
Yalnızca public metotları — Doğru. GetMethods() varsayılan olarak yalnızca public metotları döndürür.