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

คำสั่ง using ใน C# ใช้ทำอะไร

คำสั่ง using ใน C#

คำสั่ง using ใช้สำหรับจัดการทรัพยากร (Resource) ที่ต้องการการปล่อยทรัพยากรอย่างชัดเจน เช่น ไฟล์ การเชื่อมต่อฐานข้อมูล สตรีม เป็นต้น โดยจะเรียกเมธอด Dispose() อัตโนมัติเมื่อจบบล็อก using

วัตถุประสงค์หลัก

  • จัดการทรัพยากรแบบ Deterministic (ปล่อยทรัพยากรทันทีเมื่อไม่ได้ใช้)
  • ป้องกัน Memory Leak และ Resource Leak
  • โค้ดสะอาดกว่าการใช้ try-finally แบบ thủ động

ตัวอย่างการใช้งาน

using System;

class SystemResource : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("C - Resource Disposed");
    }
}

class Demo
{
    static void Main()
    {
        using (SystemResource res = new SystemResource())
        {
            Console.WriteLine("A - Inside using block");
        } // Dispose() ถูกเรียกที่นี่อัตโนมัติ

        Console.WriteLine("B - After using block");
    }
}

ผลลัพธ์

A - Inside using block
C - Resource Disposed
B - After using block

รูปแบบอื่นๆ

  • Using Declaration (C# 8.0+): using var res = new SystemResource(); (ไม่ต้องมีบล็อก curly braces ทรัพยากรจะถูกปล่อยเมื่อจบ Scope)
  • หลายทรัพยากรใน using เดียว: using (var f1 = new FileStream(...); var f2 = new FileStream(...)) { ... }