日期:2014-05-18 浏览次数:20595 次
using System;
using System.Collections.Generic;
using System.Reflection;
namespace ConsoleApplication5 {
internal class Program {
private static void Main(string[] args) {
SomeClass obj = new SomeClass(1, "some str");
List<object> values = GetPropertyValues(obj);
foreach (object o in values ?? new List<object>()) {
Console.WriteLine(o);
}
Console.ReadLine();
}
private static List<object> GetPropertyValues<T>(T t) {
List<object> result = new List<object>();
PropertyInfo[] info = typeof (T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo propertyInfo in info) {
result.Add(propertyInfo.GetValue(t, new object[0]));
}
return result;
}
private class SomeClass {
public SomeClass(int var1, string var2) {
this.var1 = var1;
this.var2 = var2;
}
public int Var1 {
get { return var1; }
}
public string Var2 {
get { return var2; }
}
private int var1;
private string var2;
}
}
}
------解决方案--------------------
通过反射实现
http://www.cnblogs.com/Dorion/archive/2007/07/02/803413.html