接口/抽象类 IEnumerable<T> 方法,其中 t 是特定的



我有一个c#抽象类,我用它作为一种接口

public abstract class ExcelParser
{
    protected FileInfo fileInfo { get; set; }
    protected bool FileIsValidExcelFile()...
    protected virtual string GetCellValue(int row, int column)...
    protected virtual int GetColumnLocation(string columnHeader)...
    public abstract IEnumerable<T> Parse();
}

我的问题是抽象的IEnumerable的T方法,Parse()。

我的问题是,我希望该方法返回特定类型的IEnumerable,但我不关心该类型在抽象级别是什么。我只希望继承类特定于返回的IEnumerable。

忽略这不能编译的事实,我遇到的另一个问题是表示层的执行。

        private string BuildSql(string fileName, bool minifySqlText, bool productCodeXref)
    {
        string result = string.Empty;
        ISqlBuilder sqlBuilder;
        ExcelParser excelParser;
        try
        {
            if (productCodeXref)
            {
                excelParser = new ProductCodeXrefExcelParser(fileName);
                var productCodeXrefs = excelParser.Parse();
                sqlBuilder = new ProductCodeXrefSqlBuilder(productCodeXrefs)
            }
            else
            {
                excelParser = new VendorExcelParser(fileName);
                var vendors = excelParser.Parse();
                sqlBuilder = new VendorSqlBuilder(vendors);
            }
            result = sqlBuilder.GetSql();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message, "USER ERROR",
                MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
        }
        return result;
    }

这是目前表示层的一个粗略实现,但我不知道这是否会工作。我提出这个问题的原因是因为我有另一个ExcelParser的实现,它确实编译了,但这需要我具体说明ExcelParser是什么,例如…

ExcelParser<Vendor>

…这完全违背了这样做的目的。

我知道这一点,因为我尝试了下面链接的类似解决方案,但是我的类/接口要求我指定类型。=>如何返回IEnumerable<从方法>

有没有办法1)让抽象类或接口中的方法返回T的IEnumerable,但在实现时不关心该类型是什么,并且2)确保接口/抽象类不关心Parse方法返回的是什么类型?

有没有办法

1)在抽象类或接口中有一个返回IEnumerable<T>的方法,但在实现时不关心该类型是什么

2)确保接口/抽象类不关心Parse方法返回的是什么类型?

是-使抽象类泛型:

public abstract class ExcelParser<T>

这个具体类看起来像:

public class VendorExcelParser : ExcelParser<Vendor>

和将包含从Excel数据创建Vendor实例的逻辑-尽可能地利用基本抽象方法。

您必须以某种方式指定类型以实现T的类型:它必须能够隐式确定(例如;按用法:Foo.Get<T>(T input), Foo.Get(""),或静态确定。Foo.Get<vendor>()

如果您的表示层不知道类型,那么我就不知道您打算如何使用泛型类来实现这一点。.Parse()需要以某种方式返回一个类型。可能您可以使用接口来完成这里的预期功能:如果返回的对象将坚持一个分类模式,那么您不必关心类型是什么,只要它符合接口即可。

根据您的使用情况,IEnumerable<object>可能是合适的?

最新更新