C#泛型 - 知道在抽象方法中使用哪个派生类

我正在处理一个 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能够在我的方法中返回一个列表。


我试图弄清楚如何做到这一点,以尽量减少编写将数据从文件中提取到每个单独的派生处理器类中的代码。


有没有办法做到这一点,或者这只是泛型的糟糕编程?


跃然一笑
浏览 128回答 2
2回答

哔哔one

你的otherClass.doProcess()方法声明如下public&nbsp;List<T>&nbsp;doProcess<T>()&nbsp;where&nbsp;T&nbsp;:&nbsp;class,&nbsp;new()所以这需要T是一个引用类型并且有一个默认的无参数构造函数。在调用方法中,您只限于T实现FileType接口:List<T>&nbsp;getValuesFromFile<T>()&nbsp;where&nbsp;T:FileType这还不够。接口也可以由值类型实现,它没有说明构造函数。因此,您必须将约束更改为:List<T>&nbsp;getValuesFromFile<T>()&nbsp;where&nbsp;T:&nbsp;class,&nbsp;FileType,&nbsp;new()(请注意,class约束必须是约束声明中的第一个)。

Smart猫小萌

您可以通过以下约束来确保 T 是引用类型:where&nbsp;T&nbsp;:&nbsp;class,&nbsp;FileType我很难确切地理解您要做什么,因此我无法提供有关您使用泛型的更一般性的指导。
打开App,查看更多内容
随时随地看视频慕课网APP