2012-01-10 18 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