gpt4 book ai didi

c# - 遍历数组

转载 作者:行者123 更新时间:2023-11-30 19:07:51 25 4
gpt4 key购买 nike

遍历数组不是问题,但如果我只想在调用方法时递增怎么办?

我什至不确定这是否可行,但有没有更简单的方法来做到这一点

    int counter;
string[] myArray = {"foo", "bar", "something", "else", "here"};

private string GetNext()
{
string myValue = string.Empty;

if (counter < myArray.Length) {
myValue = myArray [counter];
} else {
counter = 0;
}

counter++;

return myValue;
}

最佳答案

你想要的是一个迭代器

private IEnumerable<String> myEnumarable()
{
foreach(string i in myArray)
{
yield return i;
}
}

不过只是调用 myArray.GetEnumerator();效果相同。

你使用它

string[] myArray = { "foo", "bar", "something", "else", "here" };
IEnumerator<String> myEnum;

private string GetNext() //Assumes there will be allways at least 1 element in myArray.
{
if(myEnum == null)
myEnum = myArray.GetEnnumerator();
if(!myEnum.MoveNext())
{
myEnum.Reset();
myEnum.MoveNext();
}
return myEnum.Current;
}

关于c# - 遍历数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3048682/

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