【问题标题】:Interface/Abstract Class IEnumerable<T> Method Where T is Specific接口/抽象类 IEnumerable<T> 方法,其中 T 是特定的
【发布时间】:2015-07-13 19:29:02
【问题描述】:

我有一个 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>

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

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

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

【问题讨论】:

  • public abstract class ExcelParser&lt;T&gt;?

标签: c# generics types


【解决方案1】:

有什么办法

1) 让抽象类或接口中的方法返回 IEnumerable&lt;T&gt;,但在实现时不关心该类型是什么

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

是的 - 使抽象类通用:

public abstract class ExcelParser<T>

具体类将如下所示:

public class VendorExcelParser : ExcelParser<Vendor>

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

【讨论】:

  • 这让我大部分时间都在那里,但表示层要求我指定类型是什么,例如... ExcelParser excelParser; ...这是我真正想避免的事情。
  • 在查看了我的代码之后,我确定我在表示层中想要的东西在 C# 允许的情况下很可能是不可能的。我会将这个答案标记为正确,因为它让我大部分时间都在那里。我很可能会重新评估我的代码。
【解决方案2】:

您必须以某种方式指定类型才能实现 T 的类型:它必须能够被隐式确定(例如,通过使用:Foo.Get&lt;T&gt;(T input), Foo.Get(""),或静态确定,例如。Foo.Get&lt;vendor&gt;()

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

根据您的使用情况,IEnumerable&lt;object&gt; 可能合适吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多