code_junkie

How to pass a generic property as a parameter to a function?

Nov 11th, 2011
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.05 KB | None | 0 0
  1. delegate RET FunctionDelegate<T, RET>(T t);
  2.  
  3. void func<T, RET>(FunctionDelegate function, T param, ...)
  4. {
  5. ...
  6. return function.Invoke(param);
  7. }
  8.  
  9. value = obj.GetType().GetProperty("Foo").GetAccessors()[0].Invoke(obj,null);
  10.  
  11. obj.GetType().GetProperty("Foo").GetAccessors()[1].Invoke(obj,new object[]{value});
  12.  
  13. delegate RET FunctionDelegate<T, RET>(T t);
  14.  
  15. void func<T, RET>(FunctionDelegate<T,RET> function, T param, ...)
  16. {
  17. ...
  18. return function(param);
  19. }
  20.  
  21. SomeClass obj = new SomeClass();
  22. func<SomeClass,int>(delegate(SomeClass o){return o.Foo;},obj);
  23.  
  24. static void Method<T, U>(this T obj, Expression<Func<T, U>> property)
  25. {
  26. var memberExpression = property.Body as MemberExpression;
  27. //getter
  28. U code = (U)obj.GetType().GetProperty(memberExpression.Member.Name).GetValue(obj, null);
  29. //setter
  30. obj.GetType().GetProperty(memberExpression.Member.Name).SetValue(obj, code, null);
  31. }
  32.  
  33. DbComputerSet cs = new DbComputerSet();
  34. cs.Method<DbComputerSet, string>(set => set.Code);
Add Comment
Please, Sign In to add comment