14 Ekim 2016 Cuma

PropertyInfo Sınıfı

Giriş
Şu satır dahil edilir.
using System.Reflection;  // reflection namespace
Constructor
Bir Type nesnesinden isim ile elde edilir.
object obj = ...;
PropertyInfo textProperty = obj.GetType().GetProperty("Text");
Propertyler isimlerine göre süzülerek şöyle elde edilir. Type sınıfının BindingFlags bayrağı almayan GetProperties() metodu kullanılıyor.
var props = obj.GetType().GetProperties().ToList();
var someProps = props.Where(f => f.Name.Contains("PropertyNameYear")).ToList();
Propertyler bazı özelliklerine (BindingFlags) göre süzülerek şöyle elde edilir.
object obj = ...;
IEnumerable<PropertyInfo> argsProperties = obj.GetType().GetProperties(
                               BindingFlags.Public | 
                               BindingFlags.Instance | 
                               BindingFlags.DeclaredOnly);
Public ve static olanlar şöyle elde edilir.
PropertyInfo[] propertyInfos = 
obj.GetType().GetProperties(BindingFlags.Public |
                            BindingFlags.Static);
CanWrite Alanı
Şöyle yaparız.
if(textProperty.CanWrite) {...}
GetValue metodu
Object döndüğü için boxing yapar. Şöyle yaparız.
object obj = ...;
PropertyInfo propertyInfo = ...;
object value = propertyInfo.GetValue(obj);
GetValue metodu - Index
Null verirsek yukarıdaki GetValue ile aynı işi görür. Şöyle yaparız.
propertyInfo.GetValue(obj, null)
Name Alanı
Şöyle yaparız.
Console.WriteLine(propertyInfo.Name);
PropertyType Alanı
Şöyle yaparız.
if(propertyInfo.PropertyType == typeof(double)) {...}
Şöyle yaparız.
if (propertyInfo.PropertyType.IsGenericType){...}
Şöyle yaparız.
if (propertyInfo.PropertyType.IsValueType) {...}
SetValue metodu
Şöyle yaparız.
object obj = ...;
PropertyInfo propertyInfo = obj.GetType().GetProperty("Text");
propertyInfo.SetValue(obj, "0%", null);



Hiç yorum yok:

Yorum Gönder