Skip to content

Instantly share code, notes, and snippets.

@forcewake
Created February 20, 2014 15:37
Show Gist options
  • Save forcewake/9116508 to your computer and use it in GitHub Desktop.
Save forcewake/9116508 to your computer and use it in GitHub Desktop.
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