簡體   English   中英

c# 如何在工廠方法中返回指定通用 class 的 class

[英]c# How to return a class that specify a generic class in factory method

我想知道是否有可能做一個像這樣的方法而不會在返回時出現丑陋的演員?

    public static AbstractFileReader<T> GetReader<T>(string filename, T data)
    {
        if(data is string)
        {
            return GetTextFileReader(filename) as AbstractFileReader<T>;
        }
        else if(data is byte[])
        {
            return GetBytesFileReader(filename) as AbstractFileReader<T>;
        }
        else
        {
            Debug.LogError("There is no reader for that type of data : " + data.GetType().ToString());
            return null;
        }
    }

為了簡單起見,這是我的架構:

> AbstractFileReader<T> => The generic base class
> AbstractTextFileReader : AbstractFileReader<string> => an abstract class
> StandaloneTextFileReader : AbstractTextFileReader => the final implementation

我的第一個想法是做一個這樣的方法:

    public static AbstractFileReader<T> GetReader<T>(string filename, T data)
    {
        if(data is string)
        {
            return StandaloneTextFileReader(filename);
        }
        else if(data is byte[])
        {
            return StandaloneBytesFileReader(filename);
        }
        else
        {
            Debug.LogError("There is no reader for that type of data : " + data.GetType().ToString());
            return null;
        }
    }

但似乎我的編譯器不接受它。 有沒有辦法做到這一點? 謝謝

Generics 在這里對您沒有任何幫助。

您目前使用的所有T是指定參數之一的類型(除了查詢其類型外,您甚至不使用它)。 您可以像AbstractFileReader GetReader(string filename, Object data)一樣輕松地編寫它。

generics 的全部意義在於不關心Type 是什么(盡管您可以對其進行限制),並且通用 class 公開的所有方法都以相同的方式運行,無論 Type T是什么(例如, List s)。

這不是這里的情況。

因此,您根本不應該在這里使用 Generics。 只需在某個地方有一個GetReaderForStringGetReaderForBytes方法,並根據需要返回一個StandaloneTextFileReaderStandaloneBytesFileReader (或完全放棄這些方法,只new適當的類)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM