我正在处理一个 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,我希望在我的 BaseFileProcessor类中编写某种方法,以便能够从文件中获取值,如下所示:
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能够在我的方法中返回一个列表。
我试图弄清楚如何做到这一点,以尽量减少编写将数据从文件中提取到每个单独的派生处理器类中的代码。
有没有办法做到这一点,或者这只是泛型的糟糕编程?
哔哔one
Smart猫小萌
相关分类