将类作为参数传递给泛型函数

时间:2019-01-30 10:53:29

标签: c#

我正在使用这个简洁的classes将MySQL数据库中的数据表映射到对象中。 现在,我想编写一个泛型函数来返回各种不同类的列表,以便我可以调用:

List<Person> persons = ReadDataTable<Person>();
List<Car> persons = ReadDataTable<Car>();

还有更多的课程。

但是我不理解如何在通用函数中创建对象DataNamesMapper:

public List<T> ReadDataTable<T>()
{   
  List<T> parsedObjects = new List<T>();       
  DataNamesMapper<typeof(T)> mapper = new DataNamesMapper<typeof(T)> (); //<- error
  DataNamesMapper<Person> mapper = new DataNamesMapper<Person> (); //<- no error, non-generic
  //...query data, map and fill list
  return parsedObjects;
}

DataMapper已定义:

public class DataNamesMapper<TEntity> where TEntity : class, new()
{
...
}

这可能吗?

1 个答案:

答案 0 :(得分:3)

DataNamesMapper是开放类型。要使其接近T,您需要使用以下语法:

DataNamesMapper<T> mapper = new DataNamesMapper<T>();