迭代虽然数组不是问题,但是如果我只想在调用方法时才增加它呢?
我甚至不确定这是否有用,但有更简单的方法吗
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;
}
答案 0 :(得分:5)
你想要的是一个迭代器
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;
}
答案 1 :(得分:3)
您可以尝试这样做:
private string GetNext()
{
string result = myArray[counter];
counter = (counter + 1) % myArray.Length;
return result;
}
您的代码有一个错误,“foo”只会在第一次返回。
foo bar something else here <-- oops! bar something else here
答案 2 :(得分:2)
如果我理解你想要做什么,我相信你需要做的只是在数组上调用GetEnumerator()方法。 Enumerator对象有一个MoveNext()方法,它移动到列表中的下一个项目,如果有效则返回true
,如果没有则返回false
。您使用Current
属性读取了枚举数的值,并且可以使用Reset
将计数器重置为0
答案 3 :(得分:2)
您发布的示例基本上是枚举器的实现,所以是的,它可以工作。
string[] _array = {"foo", "bar", "something", "else", "here"};
IEnumerable<String> GetEnumarable()
{
foreach(string i in _array)
yield return i;
}
如果您想使用自定义数据结构执行此操作,或者希望在移动到下一个元素时添加更多逻辑(即延迟加载,流数据),您可以自己实现IEnumerator
接口。
示例强>
public class EnumeratorExample : IEnumerator
{
string[] _array;
// enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -1;
public EnumeratorExample(string[] array)
{
_array = list;
}
public bool MoveNext()
{
++position;
return (position < _array.Length);
}
public void Reset()
{
position = -1;
}
object IEnumerator.Current
{
get { return Current; }
}
public string Current
{
get
{
try
{
return _array[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException("Enumerator index was out of range. Position: " + position + " is greater than " + _array.Length);
}
}
}
}
<强>参考强>
- IEnumerable Interface
答案 4 :(得分:0)
int x=0;
while ( x<myArray.length){
if(condition){
x++;
system.out.print(myArray[x]);
}
}