Convert typeof (T) to T

I have this general function:

public List<T> GetList<T>() {
    var businesType = typeof(T);
    var databaseType = AutoMapperConfiguration.TypeMapping[businesType];

    var databaseEntityList = DataModelAccess.GetEntityList(databaseType);

    var businessEntityList = Mapper.Map(databaseEntityList, databaseEntityList.GetType(), typeof(List<T>));
    return (List<T>)businessEntityList;

}

But what I want is to call DataModelAccess instead like this:

DataModelAccess.GetEntityList(databaseType);

- send a database type of type Generic, for example:

DataModelAccess.GetEntityList<DatabaseType>();

to return this method, for example List<T>.

Thanks! Postscript Definition DataModelAccess.GetEntityList (databaseType):

public static List<object> GetEntityList(Type databaseType)
{
    //get data from database
    //retunt it as List<object> <= and I dont like that
}
+4
source share
2 answers

A function very similar to yours GetList<T>should solve this problem for you.

public List<T> GetEntityList<T>() { }

Then you can call it

typeof(DataModelAccess)
    .GetMethod("GetEntityList")
    .MakeGenericMethod(databaseType)
    .Invoke();

Hope this helps.

+2
source

If your method GetEntityListreturns a general one List<object>, but all its elements are of the same type, you can use IEnumerable.Cast<T>to turn it into List<T>:

List<object> result = DataModelAccess.GetEntityList(databaseType);
List<T> databaseEntityList = result.Cast<T>().ToList();

, , .

+2

Source: https://habr.com/ru/post/1623881/


All Articles