码迷,mamicode.com
首页 > 其他好文 > 详细

利用Lambda获取类中属性名称

时间:2016-05-03 22:19:38      阅读:791      评论:0      收藏:0      [点我收藏+]

标签:

 1     public class TypeInfoHelper
 2     {
 3         public static string GetPropertyName<T>(Expression<Func<T, dynamic>> property)
 4         {
 5             var propertyName = string.Empty;
 6             var body = property.Body;
 7             if (body.NodeType == ExpressionType.Convert)
 8             {
 9                 var o = (body as UnaryExpression).Operand;
10                 propertyName = ((o as MemberExpression).Member as PropertyInfo).Name;
11             }
12             else if (body.NodeType == ExpressionType.MemberAccess)
13             {
14                 propertyName = ((body as MemberExpression).Member as PropertyInfo).Name;
15             }
16             return propertyName;
17         }
18     }

先定义个实体用来测试:

1     public class Product
2     {
3         public int Id { get; set; }
4         public string Name { get; set; }
5         public string Description { get; set; }
6     }

使用:

1    var feildName = TypeInfoHelper.GetPropertyName<Product>(s => s.Description);
2    Console.WriteLine(feildName);

技术分享

利用Lambda获取类中属性名称

标签:

原文地址:http://www.cnblogs.com/zuqing/p/5456562.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!