• 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. }

  • 相关阅读:
    [.NET 6] IHostedService 的呼叫等等我的爱——等待Web应用准备就绪
    8位微控制器上的轻量级SM2加密算法实现:C语言详细指南与完整代码解析
    8 迭代与列表生成式
    警惕!Python 中少为人知的 10 个安全陷阱!
    RK3588 USB蓝牙调试
    头歌 MySQL数据库 - 初识MySQL
    UE4 通过按键控制Pawn比例大小
    python -- PyQt5(designer)中文详细教程(四)事件和信号
    C语言switch语句判断星期
    fcntl函数 非阻塞轮询
  • 原文地址:https://blog.csdn.net/szy759590387/article/details/126887887