แบบฝึกหัด C#

record คำสั่งซื้อที่เปลี่ยนไม่ได้

อัปเดตข้อมูลที่เปลี่ยนไม่ได้ด้วยนิพจน์ with

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

record ทำให้โมเดลแบบอิงค่ากระชับและคัดลอกได้อย่างปลอดภัย

record เดิมยังอยู่ ขณะที่สำเนาได้สถานะใหม่

ตัวอย่าง C# ที่รันได้

C#
รันโค้ด →
Program.cs
using System;
record Order(int Id, string Status);
class Program
{
    static void Main()
    {
        var pending = new Order(7, "Pending");
        var shipped = pending with { Status = "Shipped" };
        Console.WriteLine($"{pending.Status} -> {shipped.Status}");
    }
}
ผลลัพธ์ที่คาดหวัง
Pending -> Shipped

ฝึกกับดีบักเกอร์

ตั้ง breakpoint ที่การกำหนดค่าหรือเงื่อนไขสำคัญ กด Debug แล้วดูค่าตัวแปรภายในก่อนไปยังบรรทัดถัดไป