【问题标题】:C# Generics - Know which derived class to use in an Abstract MethodC# 泛型 - 知道在抽象方法中使用哪个派生类
【发布时间】: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


【解决方案1】:

您的 otherClass.doProcess() 方法声明如下

public List<T> doProcess<T>() where T : class, new()

所以这要求T 是一个引用类型并且有一个默认的无参数构造函数

在调用方法中你只限制T实现FileType接口:

List<T> getValuesFromFile<T>() where T:FileType

这还不够。接口也可以由值类型实现,它没有说明构造函数。因此,您必须将约束更改为:

List<T> getValuesFromFile<T>() where T: class, FileType, new()

(注意class 约束必须是约束声明中的第一个)。

【讨论】:

    【解决方案2】:

    你可以通过约束来确保 T 是一个引用类型:

    where T : class, FileType
    

    我很难准确地理解你想要做什么,所以我不能更一般地为你使用泛型提供指导。

    【讨论】:

    • @ScottHannen:在 .NET 中并非如此。允许structs 实现接口。
    • 就是这样 - 谢谢! - 只是因为Rene先回答,我想公平并奖励他积分,但非常感谢你!!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多