Skip to main content
 首页 » 编程设计

c#之如何以 ListT> 作为参数从泛型方法中读取值

2024年02月23日24birdshome

也许是个愚蠢的问题,我可以从列表参数中读取所有属性,但不能读取 <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); 
    } 

感谢您的帮助。

请您参考如下方法:

问题是您正在从新实例读取值(可以简单地写成 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); 
    } 
}