fork(1) download
  1. using System;
  2. using System.Linq;
  3. using System.Linq.Expressions;
  4.  
  5. public class Test {
  6.  
  7. class Tst {
  8. public int a;
  9. public int b;
  10. public int c;
  11. }
  12.  
  13. public static Func<T,object[]> MakeFieldGetter<T>() {
  14. var arg = Expression.Parameter(typeof(T), "arg");
  15. var body = Expression.NewArrayInit(
  16. typeof(object)
  17. , typeof(T).GetFields().Select(f => (Expression)Expression.Convert(Expression.Field(arg, f), typeof(object)))
  18. );
  19. return (Func<T,object[]>)Expression
  20. .Lambda(typeof(Func<T,object[]>), body, arg)
  21. .Compile();
  22. }
  23.  
  24. public static void Main() {
  25. var tst1 = new Tst {a=1,b=2,c=3};
  26. var tst2 = new Tst {a=5,b=7,c=9};
  27. var getter = MakeFieldGetter<Tst>();
  28. foreach (var f in getter(tst1)) {
  29. Console.Write("{0} ", f);
  30. }
  31. Console.WriteLine();
  32. foreach (var f in getter(tst2)) {
  33. Console.Write("{0} ", f);
  34. }
  35. }
  36.  
  37.  
  38. }
Success #stdin #stdout 0.09s 34328KB
stdin
Standard input is empty
stdout
1 2 3 
5 7 9