利用Lambda获取类中属性的名称

 public class TypeInfoHelper
    {
       public static string  GetClassPropertiesName<TClass, TResult>(Expression<Func<TClass, TResult>> propery)
        {
            var body = propery.Body.ToString();
            return body.Substring(body.LastIndexOf(".") + 1);
        }

    }

调用如下:

  public class MyClass
    {
        public string Name { get; set; }

        public List<string> UserName { get; set; }
    }

  var name = TypeInfoHelper.GetClassPropertiesName<MyClass,List<string>>(s => myClass.UserName);

 

posted @ 2012-04-10 11:13  代码哥  阅读(2971)  评论(1编辑  收藏  举报