通用方法可能是一个愚蠢的问题,我可以读取列表参数的所有属性,但不能在<T>
字段中的值。如何读取值列表<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);
}
感谢您的帮助。
究竟什么是你的问题? – 2012-01-10 17:27:54
你说'--failed'但什么** **究竟失败了吗?它是一个编译错误?运行时?什么? – 2012-01-10 17:30:40
你不需要说'XT '实例,因为你只需要调用'GetType()' 。事实上,你不需要在任何实例上调用'GetType()'。你可以说'typeof(T).GetProperties()'。 – phoog 2012-01-10 18:42:47