簡體   English   中英

C#通用工廠模式,但未說明通用類型

[英]C# generic factory pattern without stating the type of generic

我正在研究一個C#項目,以分析各種文件。 為此,我創建了以下類型的類結構:

interface FileType {}
    class FileType1 : FileType {}
    class FileType2 : FileType {}

abstract class FileProcessor<T> {}
    class Processor_FileType1 : FileProcessor<FileType1> {} 
    class Processor_FileType2 : FileProcessor<FileType2> {} 

現在,我想創建一個工廠模式,該模式僅采用文件的路徑,並根據文件的內容確定要實例化2個處理器中的哪個

理想情況下(並且我知道此代碼無效),我希望代碼看起來如下:

class ProcessorFactory
{
    public FileProcessor Create(string pathToFile)
    {
        using (var sr = pathToFile.OpenText())
        {
            var firstLine = sr.ReadLine().ToUpper();

            if (firstLine.Contains("FIELD_A"))
                return new Processor_FileType1();

            if (firstLine.Contains("FIELD_Y"))
                return new Processor_FileType2();
        }
    }
}

問題是編譯器錯誤Using the generic type 'FileProcessor<T>' requires 1 type arguments因此我的程序可以執行以下操作:

public DoWork()
{
    string pathToFile = "C:/path to my file.txt";
    var processor = ProcessorFactory.Create(pathToFile);
}

並且processor變量wold可以是Processor_FileType1Processor_FileType2

我知道我可以通過將Create更改為類型參數來做到這一點,但是我希望從那時起我就不必這樣做了,它消除了基於文件中的數據來確定它的想法。

有任何想法嗎?

你很親密 您只需在對象模型中使用一個通用的IFileProcessor概念即可。

interface FileType {}
    class FileType1 : FileType {}
    class FileType2 : FileType {}

interface IFileProcessor {}  //new
abstract class FileProcessor<T> : IFileProcessor {}
    class Processor_FileType1 : FileProcessor<FileType1> {} 
    class Processor_FileType2 : FileProcessor<FileType2> {} 

並更改您的退貨類型:

public IFileProcessor Create(string pathToFile)
{
    //implementation
}

暫無
暫無

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

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