2

我正在尝试创建一个从我的 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不一定与typeofsay匹配BsonDocument。但我已经做了适当的检查。

我可以投到List<[KnownType]>List<T>

4

2 回答 2

1

您正在滥用通用语法。通用代码应该是通用的,即适用于您使用的任何类型。

您应该有不同的方法,具体取决于将要传入的类型。无论如何,将真正通用的部分变成它自己的通用方法,您的特定类型的方法可以调用它。但是让已经知道它使用什么类型的调用者根据该类型选择适当的方法,然后在每个特定于类型的方法中显式地使用该类型。

很难用你的例子来说明,但如果你能提供一个很好的最小、完整和可验证的例子来清楚地显示你在做什么,我很乐意重构它来表达我的意思。

于 2016-03-31T16:46:37.537 回答
1

如果您确定您拥有List<KnownType>与当前泛型实例化类型相匹配的类型,List<T>则可以借助中间转换将其转换为所需的泛型类型object

List<T> GetListOf<T>() {
    if (typeof(T) == typeof(String)) {
        var stringList = new List<String> { "a", "b" };
        return (List<T>)(object)stringList;
    }
    throw new NotSupportedException();
}

是否应该这样做的道德判断留给自己)

于 2016-03-31T23:27:03.870 回答