如何使用List <t>作为参数</t>读取值表格泛型方法

时间:2012-01-10 17:26:37

标签: c# generics

也许是个愚蠢的问题,我可以从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);
    }

感谢您的帮助。

2 个答案:

答案 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);
    }
}
相关问题