IEnumerable<;T>;-如何将一个方法用于两个枚举器
本文关键字:方法 一个 用于 两个 枚举 lt gt IEnumerable | 更新日期: 2023-09-27 18:27:19
这可能是一个愚蠢的问题,但我还没有找到答案。
我有一个实现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();
}