通用方法可能是一個愚蠢的問題,我可以讀取列表參數的所有屬性,但不能在<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