• Expression与Func的区别(Expression与反射的结合使用)


    1. using System;
    2. using System.Collections.Generic;
    3. using System.ComponentModel;
    4. using System.Data;
    5. using System.Drawing;
    6. using System.Linq;
    7. using System.Linq.Expressions;
    8. using System.Text;
    9. using System.Threading.Tasks;
    10. using System.Windows.Forms;
    11. namespace DataTableTest
    12. {
    13. public partial class Form1 : Form
    14. {
    15. public Form1()
    16. {
    17. InitializeComponent();
    18. }
    19. private void Form1_Load(object sender, EventArgs e)
    20. {
    21. List people = new List()
    22. {
    23. new Person(){ Name="张三", Age=20, Gender=true, Address="中山路1号"},
    24. new Person(){ Name="李四", Age=32, Gender=true, Address="黄埔路1号"},
    25. new Person(){ Name="王五", Age=25, Gender=true, Address="天河路1号"},
    26. new Person(){ Name="赵六", Age=28, Gender=true, Address="荔湾路1号"},
    27. };
    28. dataGridView1.DataSource = CustomDataTable(people, p => p.Name, p => p.Age, /*p => p.Gender,*/ p => p.Address);
    29. }
    30. //此处参数如果传的是Func,那就无法用反射解析出内部的Member,这就是Expression优于Func之处
    31. private DataTable CustomDataTable<T>(List datas, params Expressionobject>>[] columns)
    32. {
    33. DataTable dt = new DataTable();
    34. string[] colName = new string[columns.Length];
    35. int cnt = 0;
    36. foreach (var col in columns)
    37. {
    38. MemberExpression prop;
    39. if (col.Body is UnaryExpression ue && ue.NodeType == ExpressionType.Convert)
    40. {
    41. prop = ue.Operand as MemberExpression;
    42. }
    43. else
    44. {
    45. prop = col.Body as MemberExpression;
    46. }
    47. colName[cnt++] = prop.Member.Name;
    48. string attrVal = (prop.Member.GetCustomAttributes(typeof(DescriptionAttribute),false)[0] as DescriptionAttribute).Description;
    49. dt.Columns.Add(new DataColumn(attrVal));
    50. }
    51. foreach (var item in datas)
    52. {
    53. var row = dt.Rows.Add();
    54. for (int i = 0; i < colName.Length; i++)
    55. {
    56. row[i] = item.GetType().GetProperty(colName[i]).GetValue(item).ToString();
    57. }
    58. }
    59. return dt;
    60. }
    61. }
    62. public class Person
    63. {
    64. [Description("姓名")]
    65. public string Name { get; set; }
    66. [Description("年龄")]
    67. public double Age { get; set; }
    68. [Description("性别")]
    69. public bool Gender { get; set; }
    70. [Description("地址")]
    71. public string Address { get; set; }
    72. }
    73. }

  • 相关阅读:
    社科院与杜兰大学能源管理硕士项目——惊喜会随时间慢慢酝酿而出
    solr 查询以特殊符号拼接Id成的字段
    WPF页面向后端传参
    ZDH-权限模块
    2022.8.4-----leetcode.1403
    .gitignore 不生效的解决方案
    MES系统与ERP如何集成?本文告诉你答案
    骨感传导蓝牙耳机怎么样,骨感传导耳机对于我们耳道是否有保护
    【Java接口性能优化】skywalking使用
    C语言 指针初阶
  • 原文地址:https://blog.csdn.net/szy759590387/article/details/126887887