【发布时间】:2018-10-19 21:15:22
【问题描述】:
我正在开发一个 C# 项目来解析不同类型的文件。为此,我创建了以下类结构:
interface FileType {}
class FileType1 : FileType {}
class FileType2 : FileType {}
abstract class FileProcessor {}
class Processor_FileType1 : FileProcessor {} // Will use FileType1 - type of storage class
class Processor_FileType2 : FileProcessor {} // Will use FileType2 - type of storage class
因此,由于每个 FileProcessor 使用不同类型的 FileType,我希望在我的 Base FileProcessor 类中编写某种方法,以便能够从文件中获取值的:
abstract class FileProcessor
{
protected List<T> getValuesFromFile<T>() where T:FileType
{
try
{
otherClass.doProcess<T>();
}
catch (Exception ex)
{
throw new Exception("Unable to retrieve the data from the file.", ex);
}
}
}
而且,在我一直在使用的另一个库中(与解析 Excel 文件相关),我无法更改,我有以下一种方法:
public List<T> doProcess<T>() where T : class, new()
{
// the actual work
}
但是我的getValuesFromFile 方法出现错误,指出The type 'T' must be a reference Type 能够在我的方法中返回一个列表。
我试图弄清楚如何做到这一点,以尽量减少编写代码以将数据从文件中提取到每个单独的派生处理器类中。
有没有办法做到这一点,或者这只是泛型的糟糕编程?
【问题讨论】:
-
抱歉@ScottHannen 和 ReneVogt,我现在已经用违规问题更新了问题......
标签: c# generics abstract-class derived-class