简体   繁体   中英

What is the purpose of Yield and how does it work?

While perusing Twitter I spotted a tweet by a Game Developer I follow that just said;

@ChevyRay 2:44 AM - 5 Jul 2016
i give you: the stupidest 8 lines of code i've ever written that is actually used by my game's code

 static IEnumerable<int> RightAndleft { get { yield return 1; yield return -1; } } 

Immediately I looked at it and thought to myself what does this do? I'm sure the post was meant as an in-joke but I just didn't get it. So with that I went and researched yield but that didn't really answer my question.

I wondered if anyone here could shed some light on firstly what it's doing and also why.

The compiler turns this code into an enumerator. You can use this enumerator to iterate over the sequence {1, -1} :

foreach(var i in ClassName.RightAndLeft)
    Console.WriteLine(i);

results in

1
-1

Note that this property does not have two return statements and return type int . It returns an IEnumerable<int> , a sequence containing 1 and -1 .

See yield keyword for more information.

One important part to note is that the second line yield return -1; is executed after the first value has been printed out by Console.WriteLine in this example.


Since the poster is a game developer, he probably uses these two values as direction indicators and this enumeration to, well, enumerate all possible directions or something like that.

It returns IEnumerable<int> object that contains 1 and -1 .

See https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM