gpt4 book ai didi

c# - 枚举器作为参数

转载 作者:太空狗 更新时间:2023-10-30 00:33:54 24 4
gpt4 key购买 nike

好吧,让我们从这个非常简单的按钮点击方法开始

    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 是一个结构有关。您将它传递给一个方法,对其进行操作,然后返回。您的原始实例可能不会发生这种操作。

关于c# - 枚举器作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9643274/

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