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

ข้อตกลงการตั้งชื่อ (Naming Conventions) ใน C#

การตั้งชื่อที่สอดคล้องกันทำให้โค้ดอ่านง่าย บำรุงรักษาง่าย และลดข้อผิดพลาด Microsoft มีแนวทางมาตรฐานสำหรับ C#

หลักการทั่วไป (General Rules)

  • เริ่มต้นด้วยตัวอักษร หรือ underscore (_)
  • ตามด้วยตัวอักษร ตัวเลข (0-9) หรือ underscore ได้
  • ห้ามขึ้นต้นด้วยตัวเลข
  • ห้ามมีช่องว่างหรือสัญลักษณ์พิเศษ (ยกเว้น _)
  • ห้ามใช้ Reserved Keywords (เช่น class, int, if) — ยกเว้นจะเติม @ นำหน้า

การตั้งชื่อตามประเภท (Casing Styles)

ประเภทStyleตัวอย่าง
Class, Struct, Interface, Enum, Delegate, Event, NamespacePascalCaseEmployeeDetails, IComparable
Method, Property, Public Field, ConstantPascalCaseCalculateSalary, MaxValue
Parameter, Local Variable, Private FieldcamelCaseemployeeName, _age
Type Parameter (Generic)PascalCase + T prefixTEntity, TKey

รายละเอียดเฉพาะ

Class & Struct

  • ใช้ Noun หรือ Noun Phrase: Employee, OrderDetail, FileStream
  • Interface: ใช้ Prefix I + PascalCase: IDisposable, IEnumerable<T>

Method

  • ใช้ Verb หรือ Verb Phrase: CalculateTotal, GetUserById, SaveChanges
  • Boolean-returning: ใช้ Prefix Is, Can, Has: IsValid, CanExecute

Variable & Field

  • Private/Internal fields: ใช้ Prefix _ + camelCase: _firstName, _itemCount
  • Constants (const, readonly static): PascalCase: MaxRetryCount

ตัวอย่างโค้ด

namespace MyCompany.Products {        // PascalCase
    public interface IProductService { // I + PascalCase
        ProductDto GetProductById(int productId); // PascalCase method, camelCase param
    }
    
    public class ProductService : IProductService {
        private readonly ILogger _logger; // _ + camelCase
        private const int MaxCacheSize = 100; // PascalCase constant
        
        public ProductDto GetProductById(int productId) {
            var cacheKey = $"product_{productId}"; // local variable: camelCase
            // ...
        }
    }
}

เครื่องมือช่วย

  • EditorConfig + dotnet format — บังคับ Style ได้ทั่วทีม
  • StyleCop.Analyzers — ตรวจสอบ Naming rules แบบละเอียด
  • ReSharper / Rider — Refactoring และ Naming assistance