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

时间:2015-07-13 19:29:03

标签: c# generics types

我有一个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();
}

我的问题是T方法的抽象IEnumerable,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>

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

我知道这是因为我尝试了以下链接的类似解决方案,但是我的类/接口要求我指定类型。 =&GT; How do i return IEnumerable<T> from a method

有没有办法 1)在抽象类或接口中有一个方法返回一个IE的数量,但是当它被实现时不关心那个类型是什么,并且 2)确保接口/抽象类不关心Parse方法将返回什么类型?

2 个答案:

答案 0 :(得分:1)

  

有没有办法

     

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

     

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

是 - 使抽象类具有通用性:

public abstract class ExcelParser<T>

具体类看起来像:

public class VendorExcelParser : ExcelParser<Vendor>

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

答案 1 :(得分:0)

你必须以某种方式为要实现的T类型指定类型:它必须能够被隐式确定(例如,通过用法:Foo.Get<T>(T input), Foo.Get(""),或静态确定的例如。{{ 1}}

如果您的表示层无法知道类型,那么我不知道您打算如何使用泛型类这样做。 Foo.Get<vendor>()需要以某种方式返回一个类型。可能你可以使用一个接口在这里完成预期的功能:如果返回的对象将坚持各种模式,那么你不必关心类型是什么,只是它符合接口。

根据您的使用情况,.Parse()可能合适?

相关问题