2012-01-10 17 views
1

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

感謝您的幫助。

+0

究竟什麼是你的問題? – 2012-01-10 17:27:54

+1

你說'--failed'但什麼** **究竟失敗了嗎?它是一個編譯錯誤?運行時?什麼? – 2012-01-10 17:30:40

+0

你不需要說'XT '實例,因爲你只需要調用'GetType()' 。事實上,你不需要在任何實例上調用'GetType()'。你可以說'typeof(T).GetProperties()'。 – phoog 2012-01-10 18:42:47

回答

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); 
    } 
} 
+0

謝謝,這也有幫助 – kel 2012-01-10 17:49:47

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)); 
    } 
} 
+0

這看起來像問題中代碼的副本。重點是什麼? – Gabe 2012-01-10 17:33:49

+0

謝謝它的作品:)保存我的日子 – kel 2012-01-10 17:41:28

+0

我已經添加了GetValue()方法:) – ivowiblo 2012-01-10 17:45:44