Created
February 20, 2014 15:37
-
-
Save forcewake/9116508 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
ReflectedType reflectedType = new ReflectedType(); | |
PropertyInfo intProperty = typeof(ReflectedType).GetProperty("SampleInt32"); | |
SetAndGet(intProperty, reflectedType, 0); | |
SetAndGet(intProperty, reflectedType, 10); | |
SetAndGet(intProperty, reflectedType, 30); | |
Console.WriteLine(); | |
PropertyInfo strProperty = typeof(ReflectedType).GetProperty("SampleString"); | |
SetAndGet(strProperty, reflectedType, "filled"); | |
SetAndGet(strProperty, reflectedType, null); | |
SetAndGet(strProperty, reflectedType, "New value"); | |
Console.ReadKey(); | |
} | |
private static void SetAndGet(PropertyInfo property, ReflectedType reflectedType, object newValue) | |
{ | |
var getter = property.GetValueGetter<ReflectedType>(); | |
var setter = property.GetValueSetter<ReflectedType>(); | |
setter(reflectedType, newValue); | |
var value = getter(reflectedType); | |
Console.WriteLine(value); | |
} | |
} | |
public class ReflectedType | |
{ | |
public int SampleInt32 { get; set; } | |
public string SampleString { get; set; } | |
} | |
public static class PropertyInfoExtensions | |
{ | |
public static Func<T, object> GetValueGetter<T>(this PropertyInfo propertyInfo) | |
{ | |
if (typeof(T) != propertyInfo.DeclaringType) | |
{ | |
throw new ArgumentException(); | |
} | |
var instance = Expression.Parameter(propertyInfo.DeclaringType, "i"); | |
var property = Expression.Property(instance, propertyInfo); | |
var convert = Expression.TypeAs(property, typeof(object)); | |
return (Func<T, object>)Expression.Lambda(convert, instance).Compile(); | |
} | |
public static Action<T, object> GetValueSetter<T>(this PropertyInfo propertyInfo) | |
{ | |
if (typeof(T) != propertyInfo.DeclaringType) | |
{ | |
throw new ArgumentException(); | |
} | |
var instance = Expression.Parameter(propertyInfo.DeclaringType, "i"); | |
var argument = Expression.Parameter(typeof(object), "a"); | |
var setterCall = Expression.Call( | |
instance, | |
propertyInfo.GetSetMethod(), | |
Expression.Convert(argument, propertyInfo.PropertyType)); | |
return (Action<T, object>)Expression.Lambda(setterCall, instance, argument).Compile(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment