[英]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_FileType1
或Processor_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.