我正在解决一个问题,我需要一次向消费者提供一件物品并将柜台向前移动,以便下一件物品等等,直到物品用完。我想出了代码的初稿(见下文)。底层数据结构包含一个字典,该字典包含字符串作为其键,并保存另一个字典作为其值,该字典包含实体类型的对象。
我有一种感觉,我确实需要以某种方式维护状态,所以我尝试使用 yield return 语句,但不知道如何将它粘合在一起。另外我认为使用 forarch/iterator 可能需要调整,因为消费者会调用 GetNextItem() 直到它返回 false(意味着项目用完)。
private static Dictionary<string, Dictionary <uint,Entity>> dt;
private uint localCounter=0 , globalCounter = 0;
public Entity GetNextItem()
{
foreach (string key in dt.Keys )
{
if (MoveCounters(key)) //counter is moved, so process the next item
{
yield return dt[key][localCounter];
}
}
}
private bool MoveCounters(string key)
{
if (++globalCounter > dt.Count) return false; //hit the limit
if (++localCounter > dt[key].Count)
{
globalCounter++;
return true;
}
localCounter++;
return true;
}
}
public class Entity
{
Dictionary<string, string> dtValues; //contains values from CSV file.
}