簡體   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