code_junkie

Is there a delegate available for properties in C#?

Nov 12th, 2011
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. class TestClass {
  2. public void SetValue(int value) { Value = value; }
  3. public int Value { get; set; }
  4. }
  5.  
  6. TestClass tc = new TestClass();
  7. Action<int> setAction = tc.SetValue;
  8. setAction.Invoke(12);
  9.  
  10. Action<int> valueSetter = (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), tc, tc.GetType().GetProperty("Value").GetSetMethod());
  11.  
  12. Action<int> valueSetter = v => tc.Value = v;
  13.  
  14. class TestClass
  15. {
  16. public int Value { get; set; }
  17. }
  18. static void Main()
  19. {
  20. Func<TestClass, int> lambdaGet = x => x.Value;
  21. Action<TestClass, int> lambdaSet = (x, val) => x.Value = val;
  22.  
  23. var prop = typeof(TestClass).GetProperty("Value");
  24. Func<TestClass, int> reflGet = (Func<TestClass, int>) Delegate.CreateDelegate(
  25. typeof(Func<TestClass, int>), prop.GetGetMethod());
  26. Action<TestClass, int> reflSet = (Action<TestClass, int>)Delegate.CreateDelegate(
  27. typeof(Action<TestClass, int>), prop.GetSetMethod());
  28. }
  29.  
  30. TestClass foo = new TestClass();
  31. foo.Value = 1;
  32. Console.WriteLine("Via property: " + foo.Value);
  33.  
  34. lambdaSet(foo, 2);
  35. Console.WriteLine("Via lambda: " + lambdaGet(foo));
  36.  
  37. reflSet(foo, 3);
  38. Console.WriteLine("Via CreateDelegate: " + reflGet(foo));
  39.  
  40. var propertyInfo = typeof (TestClass).GetProperty ("Value");
  41.  
  42. var setMethod = property.GetSetMethod (); // This will return a MethodInfo class.
Add Comment
Please, Sign In to add comment