Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 15th, 2012  |  syntax: None  |  size: 1.52 KB  |  hits: 21  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Reflection Performance - Create Delegate (Properties C#)
  2. TestClass cwp = new TestClass();
  3. var propertyInt = typeof(TestClass).GetProperties().Single(obj => obj.Name == "AnyValue");
  4. var access = BuildGetAccessor(propertyInt.GetGetMethod());
  5. var result = access(cwp);
  6.        
  7. static Func<object, object> BuildGetAccessor(MethodInfo method)
  8. {
  9.     var obj = Expression.Parameter(typeof(object), "o");
  10.  
  11.     Expression<Func<object, object>> expr =
  12.         Expression.Lambda<Func<object, object>>(
  13.             Expression.Convert(
  14.                 Expression.Call(
  15.                     Expression.Convert(obj, method.DeclaringType),
  16.                     method),
  17.                 typeof(object)),
  18.             obj);
  19.  
  20.     return expr.Compile();
  21. }
  22.        
  23. static Action<object, object> BuildSetAccessor(MethodInfo method)
  24. {
  25.     var obj = Expression.Parameter(typeof(object), "o");
  26.     var value = Expression.Parameter(typeof(object));
  27.  
  28.     Expression<Action<object, object>> expr =
  29.         Expression.Lambda<Action<object, object>>(
  30.             Expression.Call(
  31.                 Expression.Convert(obj, method.DeclaringType),
  32.                 method,
  33.                 Expression.Convert(value, method.GetParameters()[0].ParameterType)),
  34.             obj,
  35.             value);
  36.  
  37.     return expr.Compile();
  38. }
  39.        
  40. var accessor = BuildSetAccessor(typeof(TestClass).GetProperty("MyProperty").GetSetMethod());
  41. var instance = new TestClass();
  42. accessor(instance, "foo");
  43. Console.WriteLine(instance.MyProperty);
  44.        
  45. public class TestClass
  46. {
  47.     public string MyProperty { get; set; }
  48. }