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

ใช้ #region directive ที่ไหนใน C#?

#region และ #endregion เป็น Preprocessor Directives ใช้จับกลุ่มโค้ดเพื่อให้สามารถย่อ/ขยาย (Collapse/Expand) ได้ใน Visual Studio Editor ช่วยจัดระเบียบโค้ดขนาดใหญ่

รูปแบบ

#region ชื่อพื้นที่
// โค้ดที่ต้องการจับกลุ่ม
#endregion

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

using System;

#region Class Definition
class MyClass { }
#endregion

class Demo
{
    #region Variables
    int a;
    #endregion

    static void Main()
    {
        #region Body
        Console.WriteLine("Example showing the usage of region directive!");
        #endregion
    }
}

ผลลัพธ์

Example showing the usage of region directive!

แนวทางปฏิบัติที่ดี: ใช้จับกลุ่มโค้ดที่เกี่ยวข้องกัน (Fields, Properties, Methods, Events) หรือแยกโค้ดที่สร้างโดยเครื่องมือ (Generated Code) ไม่ควรใช้ซ้อนกันลึกเกินไป