玩玩反射 - 刚写的一个动态获取属性值的例子
2023-09-11 14:16:57 时间
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ReflectionTest { public class Employee { public string Name { get; set; } public int Age { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace ReflectionTest { public class GenericReflectionHelper<T> { public static List<string> GetListString(List<T> srcList, Dictionary<string, string> keyDict) { string row = string.Empty; int i = 0; List<string> result = new List<string>(); foreach (T elem in srcList) { Type type = elem.GetType(); row = string.Empty; i = 0; foreach (KeyValuePair<string, string> dictElem in keyDict) { PropertyInfo propertyInfo = type.GetProperty(dictElem.Key); string rowValue = propertyInfo.GetValue(elem, null).ToString(); if (i == 0) row += dictElem.Value + ": " + rowValue; else row += ", " + dictElem.Value + ": " + rowValue; i++; } result.Add(row); } return result; } } }
call method:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ReflectionTest { class Program { static void Main(string[] args) { List<Employee> employees = new List<Employee>(); employees.Add(new Employee { Name = "David", Age = 33 }); employees.Add(new Employee { Name = "Neil", Age = 34 }); employees.Add(new Employee { Name = "Tony", Age = 27 }); Dictionary<string, string> dict = new Dictionary<string, string>(); dict.Add("Name", "姓名"); dict.Add("Age", "年龄"); List<string> result = GenericReflectionHelper<Employee>.GetListString(employees, dict); foreach(string row in result) Console.WriteLine(row); } } }
运行结果:
姓名: David, 年龄: 33
姓名: Neil, 年龄: 34
姓名: Tony, 年龄: 27
相关文章
- HTML 全局属性_02
- C#反射获取属性值和设置属性值
- JS 对象的属性如果没有就初始化
- java获取实体类的属性和值
- 【Java】+反射1+获取属性/成员变量 的名称及类型
- 【Java】+反射2+设置属性/成员变量 的值
- 用jQuery的attr()设置option默认选中无效的解决 attr设置属性失效
- 【SpringBoot】配置文件的加载与属性值的绑定
- DedeCms 标签中channelartlist设置属性标签样式的方法
- react组件三大核心属性之一refs;react中的事件处理
- 【C#进阶3-1】C#特性、反射、属性
- Thymeleaf常用语法:HTML属性设置
- viewer.js 显示图片名称和照片属性
- Ajax的async属性
- C# 使用反射获取私有属性的方法
- HTML title 属性