kel
kel

Reputation: 23

How to read value form generic method with List<T> as parameter

Maybe a silly question, I can read all the properties from list parameter but not the value in the fields of <T>.

This is the structure

    public class TestRecord {
          public string StringTest { get; set; }
          public int IntegerTest { get; set; }
          public DateTime DateTimeTest { get; set; }
    }

The generic method

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

Test code for generic method

    public void TestTCode()  {
        List<TestRecord> rec = new List<TestRecord>();
        rec.Add(new TestRecord() {
             StringTest = "string",
             IntegerTest = 1,
             DateTimeTest = DateTime.Now
        });
        TestOfT<TestRecord>(rec);
    }

Thanks for your help.

Upvotes: 2

Views: 9178

Answers (2)

Jason Meckley
Jason Meckley

Reputation: 7591

the problem is you are reading the value from the new instance (which can be written simply as var xt = new T();.

if you want to get the property of the item you need to pull the value from the instance.

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

Upvotes: 4

Ivo
Ivo

Reputation: 8352

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

Upvotes: 2

Related Questions