简体   繁体   English

C#通用工厂模式,但未说明通用类型

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

I am working on a C# project to parse files of different kinds. 我正在研究一个C#项目,以分析各种文件。 In order to do this, I have created the following kind of class structure: 为此,我创建了以下类型的类结构:

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

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

Now, I would like to create a factory pattern that simply takes the path to the file and based upon the contents of the file decides which of the 2 processors to instantiate . 现在,我想创建一个工厂模式,该模式仅采用文件的路径,并根据文件的内容确定要实例化2个处理器中的哪个

Ideally (and I know this code doesn't work), I'd want my code to look something as follows: 理想情况下(并且我知道此代码无效),我希望代码看起来如下:

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();
        }
    }
}

The issue being the compiler error Using the generic type 'FileProcessor<T>' requires 1 type arguments so my program could do something like: 问题是编译器错误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);
}

and the processor variable wold be either a Processor_FileType1 or Processor_FileType2 . 并且processor变量wold可以是Processor_FileType1Processor_FileType2

I know I could do it by changing the Create to take a type argument, but I'm hoping I won't have to since then it kills the idea of figuring it out based upon the data in the file. 我知道我可以通过将Create更改为类型参数来做到这一点,但是我希望从那时起我就不必这样做了,它消除了基于文件中的数据来确定它的想法。

Any ideas? 有任何想法吗?

You're very close. 你很亲密 You just need one more concept in your object model, a common IFileProcessor. 您只需在对象模型中使用一个通用的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> {} 

And change your return type: 并更改您的退货类型:

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

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

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