2

I have the following problem: I have a list and add string items to this list. Then I create an Enumerator out of the list. When I loop through the list with the MoveNext() command it works when I access the enumerator directly. When I use the Enumerator properties to access the enumerator it doesn't work. The MoveNext() command doesn't increment the index.

Here is the code I used. Thanks a lot for your help.

public class DummyKlasse
{
    public List<string>.Enumerator enumerator;
    public List<string> list;

    public DummyKlasse()
    {
        Console.WriteLine("Test");
        list = new List<string>();
        enumerator = new List<string>.Enumerator();
    }

    public List<string>.Enumerator Enumerator
    {
        get { return enumerator; }
        set { enumerator = value;}
    }

    public List<string> List
    {
        get { return list; }
        set { list = new List<string>(value); }
    }        

    public void dummyfunction()
    {
        List.Add("test1");
        List.Add("test2");

        enumerator = List.GetEnumerator();
    }
}

public class Program
{
    static void Main(string[] args)
    {
        DummyKlasse dummyklasse = new DummyKlasse();
        dummyklasse.dummyfunction();

        //Does not work with properties
        /*
        while (dummyklasse.Enumerator.MoveNext())
        {
            Console.WriteLine(dummyklasse.Enumerator.Current);
        }
        */
        //Works WITHOUT properties
        while (dummyklasse.enumerator.MoveNext())
        {
            Console.WriteLine(dummyklasse.enumerator.Current);
        }

        Console.ReadLine();
    }
}
4

2 回答 2

4

List<T>.Enumerator是一个结构,因此在您的 while 循环中,每次访问该Enumerator属性时,您都在调用 getter,它每次都会返回一个新的枚举数副本。此枚举器将指向列表开头之前的项目,并且每次调用MoveNextCurrent都将在该枚举器的不同副本上完成。

因此,在非空列表上,MoveNext将始终返回 true,并且Enumerator.Current始终为 null。

如果您直接访问该字段,您将避免此副本和同一个枚举器被调用MoveNext和访问Current

如果您将代码更改为:

using (var enumerator = dummyklasse.Enumerator)
{
    while (enumerator.MoveNext())
    {
        Console.WriteLine(enumerator.Current);
    }
}

它将按预期工作。请注意,这与foreach语句的作用类似。

于 2013-07-17T12:14:25.577 回答
0

你为什么要在你的 中捕获一个枚举器DummyKlasse?最好只捕获列表本身(您正在这样做),并让消费者担心他们自己的枚举器。最好使用foreach循环来完成。

public class DummyKlasse
{
    public List<string> List { get; set; }

    public DummyKlasse() 
    {
        List = new List<string>();
    }

    public void Setup()
    {
        List.Add("one");
        List.Add("two");
    }
}

...

var dummy = new DummyKlasse();
dummy.Setup();

// the client does his own enumerating, not dummy.
foreach (var str in dummy.List)   
{
    Console.WriteLine(str);
}
于 2013-07-17T12:30:11.550 回答