简体   繁体   English

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

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

I am trying to make a function that generically retrieves data from my MongoDB collections.我正在尝试创建一个从我的 MongoDB 集合中检索数据的函数。 To do this I have constructed a generic method that returns a List<T> .为此,我构建了一个返回List<T>的通用方法。

My issue is that I have to create this List<T> to return, but I do so based on the typeof T .我的问题是我必须创建这个List<T>才能返回,但我这样做是基于typeof T I am not sure what I need to do to please the compiler..我不确定我需要做什么才能取悦编译器..

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);
    // ...
}

At both of the return lines I receive an error along the lines of "Cannot implicitly convert from List<[KnownType]> to List<T> . Which makes sense to me, because the typeof T does not necessarily match the typeof say BsonDocument . But I have made the proper check to do so.在两条return行中,我都收到了“无法从List<[KnownType]>隐式转换为List<T> 。这对我来说很有意义,因为typeof T不一定与typeof匹配,比如BsonDocument 。但我已经进行了适当的检查。

Can I cast List<[KnownType]> to List<T> ?我可以将List<[KnownType]>List<T>吗?

You are abusing generic syntax.您正在滥用通用语法。 Generic code should be generic , ie work with whatever type you use.通用代码应该是通用的,即与您使用的任何类型一起工作。

You should have different methods, depending on the type that will be passed in. By all means, make the truly generic parts into its own generic method, which your type-specific methods can call.您应该有不同的方法,具体取决于将传入的类型。无论如何,将真正通用的部分变成自己的通用方法,您的特定于类型的方法可以调用它。 But have the caller, who already knows what type it's using, pick the appropriate method based on that type, and then just use that type explicitly in each type-specific method.但是让已经知道它使用什么类型的调用者根据该类型选择适当的方法,然后在每个特定于类型的方法中显式使用该类型。

It's hard to say with the example you have, but if you can provide a good Minimal, Complete, and Verifiable example that shows clearly what you're doing, I would be happy to refactor it to show what I mean.用你的例子很难说,但如果你能提供一个很好的最小、完整和可验证的例子来清楚地显示你在做什么,我很乐意重构它以表明我的意思。

If you're sure you have the List<KnownType> that matches the type of current generic instantiation of List<T> you can cast it to the required generic type with the help of intermediate cast to object :如果您确定您拥有与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();
}

Leaving the moral judgement whether you should do so to yourself )将道德判断留给自己是否应该这样做)

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

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