gpt4 book ai didi

c# - IEnumerable - 如何对两个枚举器使用一种方法

转载 作者:行者123 更新时间:2023-11-30 15:28:03 27 4
gpt4 key购买 nike

这可能是个愚蠢的问题,但我还没有在任何地方找到答案。

我有一个实现 IEnumerable<KeyValuePair<int, Line>> 的简单类.它是读取我们从银行收到的 EFT 平面文件的文件读取器的基类。

派生类实现抽象 GetNext您在代码中看到的方法,并返回一个 Line 派生类型,具体取决于他们读取的行的类型。最初我让派生读者的调用者调用 GetNext在循环中直到 EOF,当它们返回 null 时。使用枚举器,他们可以改为调用 foreach,并循环读取器。

但为什么我必须实现两个枚举器?两者做完全相同的事情。而且我无法通过右键单击 => Refactor => Extract Method 重构它来调用相同的方法,因为该方法包含一个 yield 声明。但我肯定可以对两者使用一个辅助方法吗?这种方法的特征是什么?

using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace EasyDebit.BankInterface
{
public abstract class FileReader : IEnumerable<KeyValuePair<int, Line>>
{
protected int current;
protected List<string> lines = new List<string>();
private string filename;

public FileReader(string filename)
{
this.filename = filename;
this.lines = File.ReadAllLines(filename).ToList();
}

public string Filename
{
get { return filename; }
}

public IEnumerator<KeyValuePair<int, Line>> GetEnumerator()
{
Line line = null;
current = 0;

while ((line = GetNext()) != null)
yield return new KeyValuePair<int, Line>(current, line);
}

public abstract Line GetNext();

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
Line line = null;
current = 0;

while ((line = GetNext()) != null)
yield return new KeyValuePair<int, Line>(current, line);
}
}
}

最佳答案

简单地转换它以消除重复代码。

    public IEnumerator<KeyValuePair<int, Line>> GetEnumerator()
{
Line line = null;
current = 0;

while ((line = GetNext()) != null)
yield return new KeyValuePair<int, Line>(current, line);
}

public abstract Line GetNext();

System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return (IEnumerator)GetEnumerator();
}

关于c# - IEnumerable<T> - 如何对两个枚举器使用一种方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26465756/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com