利用表达式获取属性名称

 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             Person p = new Person();
 6             string name = ReflectionUtility.GetPropertyName(() => p.Age);
 7         }
 8 
 9         public static class ReflectionUtility
10         {
11             public static string GetPropertyName<T>(Expression<Func<T>> expression)
12             {
13                 MemberExpression body = (MemberExpression)expression.Body;
14 
15                 return body.Member.ReflectedType.Name + "." + body.Member.Name;
16             }
17         } 
18     }
19 
20     public class Person
21     {
22         public string Name { getset; }
23 
24         public int Age { getset; }
25     }
posted @ 2011-10-17 17:52  丁守庆  阅读(203)  评论(0编辑  收藏  举报
专业成就价值