문제

괜 찮 아 요,이 매우 간단한 버튼으로 시작하자

    private void button1_Click(object sender, EventArgs e)
    {
        int counter = 1;
        List<int> items = new int[] { 1, 2, 3 }.ToList();
        List<int>.Enumerator enm = items.GetEnumerator();

        // 1
        if (!enm.MoveNext())
            throw new Exception("Unexpected end of list");
        if (enm.Current != counter)
            throw new Exception(String.Format("Expect {0} but actual {1}", counter, enm.Current));
        counter++;

        // 2
        if (!enm.MoveNext()) 
            throw new Exception("Unexpected end of list");
        if (enm.Current != counter) 
            throw new Exception(String.Format("Expect {0} but actual {1}", counter, enm.Current));
        counter++;

        //3
        if (!enm.MoveNext())
            throw new Exception("Unexpected end of list");
        if (enm.Current != counter)
            throw new Exception(String.Format("Expect {0} but actual {1}", counter, enm.Current));
        counter++;

        if (enm.MoveNext()) 
            throw new Exception("Unexpected continuation of list");
    }
.

모든 어설 션이 정상적으로 지나가기 때문에이 방법은 아무 것도하지 않습니다.중복성을 제거하는 방법을 소개해야한다고 믿을 때까지는 일이 괜찮습니다.

    static void AssertNext(ref int counter, List<int>.Enumerator e)
    {
        if (!e.MoveNext()) 
            throw new Exception("Unexpected end of list");
        if (e.Current != counter) 
            throw new Exception(String.Format("Expect {0} but actual {1}", counter, e.Current));
        counter++;
    }

    private void button2_Click(object sender, EventArgs e)
    {
        var counter = 1;
        var items = new int[] { 1, 2, 3 }.ToList();
        var enm = items.GetEnumerator();
        AssertNext(ref counter, enm);
        AssertNext(ref counter, enm);
        AssertNext(ref counter, enm);
        if (enm.MoveNext()) throw new Exception("Unexpected continuation of list");
    }
.

비록이 리팩토링은 간단합니다 (적어도, 적어도, 나를 위해).그것은 프로그램을 깰 것입니다! assertnext의 두 번째 호출에서 열거자가 시작점으로 이미 재설정 된 것처럼 보이고 어설 션이 실패 할 수 있습니다.

나는 일어날 일을 이해할 수 없다.나는이 퍼즐을 가진 초보자처럼 느껴집니다.

내가 여기서 그리워하는 것은 무엇입니까?

도움이 되었습니까?

해결책

List.Enumerator가 구조체 인 것으로 상상해보십시오.메서드에 전달하고 조작 한 다음 반환합니다.조작은 원래의 인스턴스에 대해 일어난 일이 아닐 것입니다.

다른 팁

List<T>.Enumerator는 메소드를 남겨두면 메소드의 로컬 범위에 복사 된 값의 로컬 범위에 복사 된 다음이를 의미합니다.참조로 전달 해보십시오.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top