MongoDB コレクションから一般的にデータを取得する関数を作成しようとしています。これを行うために、 を返すジェネリック メソッドを作成しましたList<T>
。
私の問題は、List<T>
返すためにこれを作成する必要があることですが、typeof
T
. コンパイラを喜ばせるために何をする必要があるのか わかりません..
public async Task<List<T>> GetDocsAsync<T>(
CollectionTypes collection, // Enum representing my Collections
FilterDefinition<BsonDocument> search,
SortDefinition<BsonDocument> sort = null)
{
// Get BsonDocuments from the collection based on the search and sort criteria
List<BsonDocument> matchedDocs;
IMongoCollection<BsonDocument> MongoCollection = GetCollection(collection);
if (sort == null) matchedDocs = await MongoCollection.Find(search).ToListAsync();
else matchedDocs = await MongoCollection.Find(search).Sort(sort).ToListAsync();
// Return a List<T>, covert matchedDocs to List<T> if need be
Type docType = typeof(T);
if (docType == typeof(BsonDocument))
return matchedDocs;
else if (docType == typeof(LogEvent_DBDoc))
return LogEvent_DBDoc.ConvertFromBson(matchedDocs);
// ...
}
両方のreturn
行で、「 からList<[KnownType]>
に暗黙的に変換できません。は必ずしもsay と一致するとは限らないList<T>
ため、これは理にかなっています。しかし、そうするために適切なチェックを行いました。typeof
T
typeof
BsonDocument
にキャストできますList<[KnownType]>
かList<T>
?