簡體   English   中英

在通用函數中將類傳遞為參數

[英]Pass Class as Parameter in Generic Function

我正在使用這個簡潔的將數據表從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()
{
...
}

這可能嗎?

DataNamesMapper是開放類型。 要使其關閉到T您需要使用以下語法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM