Creating a Generic Field in a Class
I'm writing a file processing service to parse and process different ki开发者_如何学编程nds of transaction files. I have a generic file parser with implementations for different types of transactions as follows.
public interface IFileParser<T>
{
List<T> Parse(StreamReader fileStream);
}
public MonthlyParser : IFileParser<MonthlyTransaction>
{
public List<MonthlyTransaction> Parse(StreamReader fileStream)
{
......
}
}
public DailyParser : IFileParser<DailyTransaction>
{
public List<DailyTransaction> Parse(StreamReader fileStream)
{
.....
}
}
public enum FileTypes
{
DailyTransaction,
MonthlyTransaction
}
public class FileProcessor
{
private TransactionContext dataContext;
private IFileParser<T> fileParser;
public FileProcessor(TransactionContext dbContext)
{
dataContext = dbContext;
}
public void ProcessFile(string filePath, FileType fileType)
{
// here instantiate IFileParser based on FileType.
// parse and process file.
}
}
My problem is how do I create a field in the FileProcessor class of that generic interface to which a concrete implemenation can be assigned and used? Im also thinking of moving the instantiation to an IoC.
You have to make FileProcessor
generic too, if you want to have a field of type IFileParser<T>
.
However, it's not clear why you really need to have a field of that type anyway - why can't it be a local variable in ProcessFile
? It's also not entirely clear what you'll do with the list even when you've created it... what will you do with each element?
精彩评论