zoukankan      html  css  js  c++  java
  • 【转】C#通过Expression获取指定属性的名称

    原文:http://www.cnblogs.com/powerwu/articles/3393582.html

    大家所熟悉的是通过对象属性来访问该属性的值,或是由字符串通过反射来获取属性,并取值。今天我要说的是,通过对象的属性来获取该属性的名称,其意义在于拼接字符串时显示该名称,特别是自行拼接 SQL语句。下列代码是个简单测试类:

    复制代码
    public class TestClass  
        {          
            public int ID { get; set; }  
      
            public string Name { get; set; }  
      
            public DateTime CreateDate { get; set; }  
     } 
    复制代码

    1、直接访问属性值

    var obj = new TestClass ();  
    Response.Write(obj.ID) ; 

    2、由字符串获取指定的属性值

    using System.Reflection;  
      
    var obj = new TestClass ();  
    Response.Write(obj.GetType().GetProperty("ID").GetValue()) ; 

    3、通过对象的属性反向获取该属性的名称

    复制代码
        using System.Linq.Expressions;  
                public static string GetPropertyName<T>(Expression<Func<T,object>> expr)  
                {  
                    var rtn = "";  
                    if (expr.Body is UnaryExpression)  
                    {  
                        rtn = ((MemberExpression)((UnaryExpression)expr.Body).Operand).Member.Name;  
                    }  
                    else if (expr.Body is MemberExpression)  
                    {  
                        rtn = ((MemberExpression)expr.Body).Member.Name;  
                    }  
                    else if (expr.Body is ParameterExpression)  
                    {  
                        rtn = ((ParameterExpression)expr.Body).Type.Name;  
                    }  
                    return rtn;  
            }  
          
        Response.Write(GetPropertyName< TestClass >(p=>p.ID)) ; //输出的是 "ID" 两字母  
        Response.Write(GetPropertyName< TestClass >(p=>p. Name)) ; //输出的是 "Name" 四个字母  
        Response.Write(GetPropertyName< TestClass >(p=>p)) ; //输出的是 "TestClass" 九个字母  
    复制代码

    第三种常用在拼接自定义 SQL语句或是动态 SQL中,例如:

    var sql = "select a.ID,a.Name from dbo.TestClass";就可以这样写了

    var sql = "select a. " + GetPropertyName<TestClass>(p=>p.ID)+",a." + GetPropertyName<TestClass>(p=>p. Name)+ " from dbo." + GetPropertyName<TestClass>(p=>p);

  • 相关阅读:
    Spring简介和基础
    el表达式
    Spring MVC 文件上传下载
    el表达式的function标签
    JSTL核心标签库使用
    基于注解的SpringMVC
    new一个Object对象占用多少内存?
    leetcode-第k个排列(Java和c++版)
    使用maven构建web项目(简易版)
    leetcode-电话号码的字母组合
  • 原文地址:https://www.cnblogs.com/gossip/p/4084718.html
Copyright © 2011-2022 走看看