标签:enumeration c
这可能是一个愚蠢的问题,但我在任何地方都找不到答案.
我有一个实现IEnumerable< KeyValuePair< int,Line>>的简单类.这是文件读取器的基类,它读取我们从银行收到的EFT平面文件.
派生的类实现您在代码中看到的抽象GetNext方法,并返回Line派生的类型,具体取决于它们读取的行的类型.最初,派生读者的调用者会循环调用GetNext直到EOF,直到它们返回null.使用枚举器,他们可以改为调用foreach,并遍历阅读器.
但是为什么我必须实现两个枚举器?两者做的完全一样.而且我无法通过右键单击=>重构它来调用相同的方法.重构=>提取方法,因为该方法包含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();
}
标签:enumeration,c 来源: https://codeday.me/bug/20191029/1956948.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。