Burak Selim Senyurt
Matematik Mühendisi bir .NET Severin Yazıları...

Tek Fotoluk İpucu-25 (Runtime Value ve Extension Method)

Perşembe, 18 Ağustos 2011 15:08 by bsenyurt

Merhaba Arkadaşlar,

Özellikle Reflection kullandığımız bazı çalışma zamanı senaryolarında, nesnelerin özellik değerlerini elde etmek istediğimiz durumlar da söz konusu olabilir. Çok basit bir senaryo göz önüne alındığında bunun için bir Extension method dahi geliştirebiliriz. Nasıl mı? Winking smile

RuntimeValues.rar (23,48 kb)

Yorumlar

Eylül 7. 2011 02:16

Serkan KARAKUŞ

Yukarıda yer alan örneğinize istinadan benim yorumum aşağıda yer aldığı gibi olurdu.

using System;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass<DateTime> mc = new MyClass<DateTime> { MyProperty = 10, MyGenericProperty = DateTime.Parse("23.04.1923") };
            Console.WriteLine(mc.GetRuntimeValue<int>("MyProperty").ToString());
            Console.WriteLine(mc.GetRuntimeValue<int>("MyProperty1", -1).ToString());
            Console.WriteLine(mc.GetRuntimeValue<string>("MyProperty", "test").ToString());

            Console.WriteLine(mc.GetRuntimeValue<DateTime>("MyGenericProperty").ToString());
            Console.WriteLine(mc.GetRuntimeValue<DateTime>("MyGenericProperty1", DateTime.Now).ToString());
            Console.WriteLine(mc.GetRuntimeValue<string>("MyGenericProperty", "test").ToString());
            Console.ReadKey();
        }
    }

    static class RuntimeExtensions
    {
        public static TValue GetRuntimeValue<TValue>(this object owner, String propertyName, TValue defaultValue = default(TValue))
        {
            System.Reflection.PropertyInfo propertyInfo = owner.GetType().GetProperty(propertyName);
            if (propertyInfo != null && propertyInfo.PropertyType.Equals(typeof(TValue)))
                defaultValue = (TValue)propertyInfo.GetValue(owner, null);
            return defaultValue;
        }
    }

    class MyClass<T>
    {
        public int MyProperty { get; set; }

        public T MyGenericProperty { get; set; }
    }
}

Serkan KARAKUŞ

Yorumlar kapalı.