[英]Pass Class as Parameter in Generic Function
I'm using this neat classes to map data tables from a MySQL database into objects. 我正在使用这个简洁的类将数据表从MySQL数据库映射到对象。 Now I would like to write a generic function to return a list for a variety of different classes so I could call: 现在我想写一个泛型函数来返回各种不同类的列表,所以我可以调用:
List<Person> persons = ReadDataTable<Person>();
List<Car> persons = ReadDataTable<Car>();
and many more classes. 还有更多的课程。
But I don't unterstand how to create the object DataNamesMapper in my generic function: 但是我不会在我的泛型函数中解释如何创建对象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 is defined: DataMapper定义如下:
public class DataNamesMapper<TEntity> where TEntity : class, new()
{
...
}
Is this possible? 这可能吗?
The DataNamesMapper
is open type. DataNamesMapper
是开放类型。 To make it closed to T
you need to use this syntax: 要使其关闭到T
您需要使用以下语法:
DataNamesMapper<T> mapper = new DataNamesMapper<T>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.