玩玩反射 - 刚写的一个动态获取属性值的例子
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
技术改变世界