作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这可能是个愚蠢的问题,但我还没有在任何地方找到答案。
我有一个实现 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/
我是一名优秀的程序员,十分优秀!