mardi 20 septembre 2016

Iterator pattern and return yield [duplicate]

This question already has an answer here:

I'm trying to understand this code, why there are two returns in the same method and what does the yield actually do there?

Also, how does this know how to keep the index?

    public class MyData
    {
        private string _id;
        private List<string> _data;
        public MyData(string id, params string[] data)
        {
            _id = id;
            _data = new List<string>(data);
        }
        public IEnumerator<string> GetEnumerator()
        {
            yield return _id;
            foreach (string d in _data) yield return d;
        }
    }

Also, why does giving up the current thread's time has to be related with an iterator? i.e why this in MyData doesn't compile:

        public string foo()
        {
            yield return _id;
            yield return _data[0];
        }

The MyData code is from:

http://ift.tt/HfnnQ9

Aucun commentaire:

Enregistrer un commentaire