Guest

LosManos

By: a guest on Jan 8th, 2010  |  syntax: C#  |  size: 2.20 KB  |  hits: 272  |  expires: Never
download  |  raw  |  embed  |  report abuse
Copied
  1.     class ReflectionUtility
  2.     {
  3.  
  4.         public static string GetPropertyName<T, TReturn>(Expression<Func<T, TReturn>> expression)
  5.         {
  6.             MemberExpression body = (MemberExpression)expression.Body;
  7.             return body.Member.Name;
  8.         }
  9.  
  10.         public static string GetMethodName<T, TReturn>(Expression<Func<T, TReturn>> expression)
  11.         {
  12.             var body = expression.Body as UnaryExpression;
  13.             var operand = body.Operand as MethodCallExpression;
  14.             var argument = operand.Arguments[2] as ConstantExpression;
  15.             var methodInfo = argument.Value as System.Reflection.MethodInfo;
  16.  
  17.             return methodInfo.Name;
  18.         }
  19.  
  20.     }
  21.  
  22.  
  23.     class MyClass
  24.     {
  25.         public int MyField;
  26.         public int MyPublicProperty { get; set; }
  27.         public  string MyReadonlyProperty { get { return string.Empty; } }
  28.         public int MyMethod() { return 0; }
  29.  
  30.         private MyClass() { }   // To make sure the class doesn't need a default constructor.
  31.     }
  32.  
  33.  
  34.     class Program
  35.     {
  36.         static void Main(string[] args)
  37.         {
  38.             string fieldName = ReflectionUtility.GetPropertyName((MyClass x) => x.MyField);
  39.             Console.WriteLine(string.Format("MyClass.MyField:{0}", fieldName));
  40.             Debug.Assert("MyField" == fieldName);
  41.  
  42.             string propertyName = ReflectionUtility.GetPropertyName((MyClass x) => x.MyPublicProperty);
  43.             Console.WriteLine(string.Format("MyClass.MyPublicProperty:{0}", propertyName));
  44.             Debug.Assert("MyPublicProperty" == propertyName);
  45.  
  46.             propertyName = ReflectionUtility.GetPropertyName((MyClass x) => x.MyReadonlyProperty);
  47.             Console.WriteLine(string.Format("MyClass.MyReadonlyProperty :{0}", propertyName));
  48.             Debug.Assert("MyReadonlyProperty" == propertyName);
  49.  
  50.             string methodName = ReflectionUtility.GetMethodName<MyClass, Func<int>>((MyClass x) => x.MyMethod);
  51.             Console.Write(string.Format("MyClass.MyMethod:{0}", methodName));
  52.             Debug.Assert("MyMethod" == methodName);
  53.  
  54.             Console.Write(Environment.NewLine + "Press any key.");
  55.             Console.ReadKey();
  56.         }
  57.  
  58.     }