dimanche 24 mai 2020

How to get concrete type in generic method

I have a method that returns an interface:

private List<IFoo> GetData(string key)
{    
   ...returns a different concrete implementation depending on the key (e.g. FooBar : IFoo)
}

And I want to convert the result to a DataTable:

var result = GetData("foobar");
return ConvertToDataTable(result)

and my implementation of ConvertToDataTable looks something like this:

private DataTable ConvertToDataTable<T>(IEnumerable<T> data)
{
    //problem is typeof(T) is always IFoo - not FooBar
    PropertyInfo[] properties = typeof(T).GetProperties();

    DataTable table = new DataTable();
    foreach (var prop in properties)
    {
        table.Columns.Add(prop.DisplayName, prop.PropertyType);
    }
    //etc..
}

How can I get the underlying type in the generic ConvertToDataTable method?





Aucun commentaire:

Enregistrer un commentaire