Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

การใช้งาน yield return ใน C#

yield return ใช้สร้าง Iterator แบบ Lazy Evaluation (Deferred Execution) ควบคุม State ระหว่าง Caller และ Iterator

ตัวอย่าง: Running Total

using System;
using System.Collections.Generic;

namespace DemoApplication
{
    class Program
    {
        static List numbers = new List { 1, 2, 3, 4, 5 };

        static void Main()
        {
            foreach (int total in RunningTotal())
            {
                Console.WriteLine(total);
            }
            Console.ReadLine();
        }

        static IEnumerable RunningTotal()
        {
            int sum = 0;
            foreach (int n in numbers)
            {
                sum += n;
                yield return sum; // ส่งค่ากลับ แล้วหยุดรอ Next()
            }
        }
    }
}

Output

1
3
6
10
15

ทำงานอย่างไร?

  1. Caller เรียก foreach → เรียก RunningTotal() ได้ Enumerator
  2. Enumerator รันจนเจอ yield return → ส่งค่าให้ Caller → หยุด (Suspend)
  3. Caller ทำงานต่อ (Print) → เรียก MoveNext() → Enumerator ทำงานต่อจากจุดหยุด
  4. State (ตัวแปร sum) ถูกเก็บไว้ → ไม่ต้องคำนวณใหม่

ประโยชน์

  • Memory Efficient: ไม่ต้องสร้าง List ทั้งหมดใน Memory
  • Lazy: คำนวณต่อเมื่อถูกขอ (On-demand)
  • Infinite Sequence ได้: yield return ใน While True