我正在尝试创建一个从我的 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]>
为List<T>
。这对我来说很有意义,因为typeof
T
不一定与typeof
say匹配BsonDocument
。但我已经做了适当的检查。
我可以投到List<[KnownType]>
吗List<T>
?