也许是个愚蠢的问题,我可以从list参数中读取所有属性,但不能读取<T>
字段中的值。
这是结构
public class TestRecord {
public string StringTest { get; set; }
public int IntegerTest { get; set; }
public DateTime DateTimeTest { get; set; }
}
通用方法
public void TestOfT<T>(List<T> pList) where T:class, new() {
T xt = (T)Activator.CreateInstance(typeof(T));
foreach (var tp in pList[0].GetType().GetProperties()) {
// System.Reflection.PropertyInfo pi = xt.GetType().GetProperty("StringTest");
// object s = pi.GetValue(tp, null) ; -- failed
Debug.WriteLine(tp.Name);
Debug.WriteLine(tp.PropertyType);
Debug.WriteLine(tp.GetType().Name);
}
}
通用方法的测试代码
public void TestTCode() {
List<TestRecord> rec = new List<TestRecord>();
rec.Add(new TestRecord() {
StringTest = "string",
IntegerTest = 1,
DateTimeTest = DateTime.Now
});
TestOfT<TestRecord>(rec);
}
感谢您的帮助。
答案 0 :(得分:2)
public void TestOfT<T>(List<T> pList) where T:class, new() {
var xt = Activator.CreateInstance(typeof(T));
foreach (var tp in pList[0].GetType().GetProperties()) {
Debug.WriteLine(tp.Name);
Debug.WriteLine(tp.PropertyType);
Debug.WriteLine(tp.GetType().Name);
Debug.WriteLine(tp.GetValue(pList[0], null));
}
}
答案 1 :(得分:1)
问题是你正在读取新实例的值(可以简单地写成var xt = new T();
。
如果你想获得项目的属性,你需要从实例中提取值。
void TestOfT<T>(IEnumerable<T> list) where T: class, new()
{
var properties = typeof(T).GetProperties();
foreach (var item in list)
foreach (var property in properties)
{
var name = property.Name;
var value = property.GetValue(item, null);
Debug.WriteLine("{0} is {1}", name, value);
}
}