zoukankan      html  css  js  c++  java
  • 利用Lambda获取类中属性名称

     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);

  • 相关阅读:
    ubuntu 10.04 install network bcm4418
    linux vi commend
    api
    ubuntu安装jdk
    maven常用命令介绍
    ubuntu 10.04 install oracle11g
    putty中文乱码问题解决
    SCP不需要密码
    java command
    Ubuntu vsftpd 安装配置
  • 原文地址:https://www.cnblogs.com/zuqing/p/5456562.html
Copyright © 2011-2022 走看看