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

วิธีเขียน Single-line Comments ใน C#

ใน C# หากต้องการเพิ่มคำอธิบาย (Comment) ที่อยู่ในบรรทัดเดียว ให้ใช้เครื่องหมาย // (Double slash) คอมไพเลอร์จะละเว้นข้อความทั้งหมดหลังเครื่องหมาย // จนถึงสิ้นบรรทัด

รูปแบบ

// นี่คือ single-line comment
int i = 20;  // คำอธิบายต่อท้ายบรรทัดก็ได้

ตัวอย่างโปรแกรม

using System;

namespace Demo {
    class Program {
        static void Main(string[] args) {
            // แสดงข้อความบนหน้าจอ
            Console.WriteLine("Hello World");
            Console.ReadKey();
        }
    }
}

ผลลัพธ์

Hello World

เคล็ดลับและ Best Practices

  • อธิบาย "ทำไม" ไม่ใช่ "ทำอะไร" - โค้ดที่เข้าใจง่ายไม่ต้องอธิบายว่าทำอะไร แต่อธิบายเหตุผลหรือบริบท
  • TODO/FIXME/HACK - ใช้แท็กมาตรฐานเพื่อให้ IDE สามารถค้นหาได้
    // TODO: Implement validation logic
    // FIXME: Handle null reference case
    // HACK: Temporary workaround for API bug
  • XML Documentation Comments - ใช้ /// สำหรับสร้างเอกสารอัตโนมัติ
    /// 
    /// Calculates the sum of two integers.
    /// 
    /// First number
    /// Second number
    /// Sum of a and b
    public int Add(int a, int b) => a + b;

เปรียบเทียบ Comment Types

ประเภท Syntax ใช้เมื่อไหร่
Single-line // comment คำอธิบายสั้น บรรทัดเดียว
Multi-line /* comment */ คำอธิบายยาว หลายบรรทัด
XML Doc /// comment เอกสาร API สำหรับ IntelliSense