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{ public static List GetListString(List srcList, Dictionary keyDict) { string row = string.Empty; int i = 0; List result = new List (); foreach (T elem in srcList) { Type type = elem.GetType(); row = string.Empty; i = 0; foreach (KeyValuePair 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) { Listemployees = new List (); 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 dict = new Dictionary (); dict.Add("Name", "姓名"); dict.Add("Age", "年龄"); List result = GenericReflectionHelper .GetListString(employees, dict); foreach(string row in result) Console.WriteLine(row); } }}
运行结果:
姓名: David, 年龄: 33姓名: Neil, 年龄: 34姓名: Tony, 年龄: 27