繁体   English   中英

将 List&lt;[KnownType]&gt; 转换为 List<T> 匹配函数的返回类型?

[英]Casting List<[KnownType]> to List<T> to match function's return type?

我正在尝试创建一个从我的 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匹配,比如BsonDocument 。但我已经进行了适当的检查。

我可以将List<[KnownType]>List<T>吗?

您正在滥用通用语法。 通用代码应该是通用的,即与您使用的任何类型一起工作。

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

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

如果您确定您拥有与List<KnownType> List<T>的当前泛型实例化类型匹配的List<KnownType> ,您可以借助中间转换为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();
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM