首页 > 其他 > 详细

利用Lambda获取类中属性名称

时间:2016-05-03 22:17:10      阅读:279      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!