猿问

C#泛型工厂模式不说明泛型的类型

我正在处理一个 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变量将是 aProcessor_FileType1或Processor_FileType2。


我知道我可以通过更改Createto take a type 参数来做到这一点,但我希望从那时起我就不必这样做了,它会扼杀根据文件中的数据来计算它的想法。


有任何想法吗?


至尊宝的传说
浏览 230回答 1
1回答
随时随地看视频慕课网APP
我要回答