2010-06-15 10 views
2

배열을 반복해도 문제는 없지만 메서드를 호출 할 때만 증분을 원한다면 어떻게해야합니까? 이 작업을 것이지만, 일을 더 쉬운 방법이 있는지배열을 통해 반복

임조차 확실하지 않은이 내가 당신이하고자하는 것을 이해한다면

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

나는 내가 완전히 질문을 이해 모르겠어요. "메서드가 호출 될 때만 증분하기를 원했던가?" – Meiscooldude

+0

나는 당신이 정말로 묻는 것을 보았는 지 확신하지 못한다. - 초기화 문장을 제외하고, 누군가가 당신의 메도 번트를 부르지 않으면 아무 것도 호출되지 않는다. 다른 사람이 GetNext 함수를 호출 할 때 카운터 또는 배열 내용을 수정할 수 있다고 생각하지 않는 한 ... –

답변

5

으로 0으로 카운터를 재설정 할 수 있습니다; 같은 효과가 있습니다.

당신은 당신은 대신을 시도 할 수

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; 
} 
2

, 난 당신이합니다 (GetEnumerator를 호출하기 만하면 모든 생각) 메소드를 호출합니다. Enumerator 개체에는 목록의 다음 항목으로 이동하는 MoveNext() 메서드가 있으며 작업 할 경우 true을 반환하고 그렇지 않은 경우 false을 반환합니다.) (당신은 Current 속성 열거의 값을 읽고, 당신은 당신이 원하는 것은 그러나 단지 호출 myArray.GetEnumerator 반복자

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

에게 있습니다 Reset

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

게시 한 예제는 기본적으로 열거 자의 구현이므로 그래도 작동합니다.

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

0
int x=0; 
while (x<myArray.length){ 
    if(condition){ 
     x++; 
     system.out.print(myArray[x]); 
    } 
}