C# 将类作为泛型函数中的参数传递

C# 将类作为泛型函数中的参数传递,c#,C#,我使用这个简洁的方法将MySQL数据库中的数据表映射到对象中。 现在,我想编写一个泛型函数来返回各种不同类的列表,以便调用: List<Person> persons = ReadDataTable<Person>(); List<Car> persons = ReadDataTable<Car>(); List persons=ReadDataTable(); 列出人员=ReadDataTable(); 还有更多的课程 但我不理解如何在我的通

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

List<Person> persons = ReadDataTable<Person>();
List<Car> persons = ReadDataTable<Car>();
List persons=ReadDataTable();
列出人员=ReadDataTable();
还有更多的课程

但我不理解如何在我的通用函数中创建对象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;
}
public List ReadDataTable()
{   
List parsedObjects=新列表();

DataNamesMapper mapper=newdatanamesmapper();//数据名称映射器是开放类型。要使其关闭到
T
,需要使用以下语法:

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

尝试
DataNamesMapper
而不是
DataNamesMapper
@AleksAndreev我想你应该把它作为一个答案,简短但正确。这给了我一个错误:类型“T”必须是一个引用类型,才能在泛型类型或方法“DataNamesMapper”中将其用作参数“TEntity”@flex我认为这是因为你定义了
ReadDataTable
方法没有约束,但是
DataNamesMapper
有2:
类,new()
。所以在ReadDataTable声明中添加一个
where
子句AHH..我不明白!非常感谢您的帮助!
DataNamesMapper<T> mapper = new DataNamesMapper<T>();