Access Specifiers (Access Modifiers) ใน C#.NET
ควบคุม Visibility (ความมองเห็น) ของ Type และ Member ระหว่าง Assembly และ Derived Classes
6 Access Modifiers
| Modifier | ภายใน Class | Derived Class (Same Assembly) | Other Class (Same Assembly) | Derived Class (Other Assembly) | Other Class (Other Assembly) |
|---|---|---|---|---|---|
public | ✓ | ✓ | ✓ | ✓ | ✓ |
protected internal | ✓ | ✓ | ✓ | ✓ | ✗ |
protected | ✓ | ✓ | ✗ | ✓ | ✗ |
internal | ✓ | ✓ | ✓ | ✗ | ✗ |
private protected | ✓ | ✓ | ✗ | ✗ | ✗ |
private | ✓ | ✗ | ✗ | ✗ | ✗ |
คำอธิบายแต่ละ Modifier
1. public
เข้าถึงได้จากที่ไหนก็ได้ ไม่มีข้อจำกัด
2. private (Default สำหรับ Class Members)
เข้าถึงได้เฉพาะภายใน Class เดียวกันเท่านั้น
3. protected
เข้าถึงได้ใน Base Class และ Derived Class (แม้จะอยู่ Assembly ต่างกัน)
4. internal (Default สำหรับ Top-level Types)
เข้าถึงได้ภายใน Assembly เดียวกันเท่านั้น
5. protected internal
Union ของ protected และ internal: เข้าถึงได้ใน Same Assembly หรือ Derived Class ใน Other Assembly
6. private protected (C# 7.2+)
Intersection ของ protected และ internal: เข้าถึงได้ใน Derived Class ภายใน Same Assembly เท่านั้น
ตัวอย่างการใช้งาน
public class BaseClass
{
public int PublicField = 1;
protected int ProtectedField = 2;
internal int InternalField = 3;
protected internal int ProtIntField = 4;
private protected int PrivProtField = 5;
private int PrivateField = 6;
}
public class DerivedSameAssembly : BaseClass
{
void Test()
{
Console.WriteLine(PublicField); // OK
Console.WriteLine(ProtectedField); // OK
Console.WriteLine(InternalField); // OK
Console.WriteLine(ProtIntField); // OK
Console.WriteLine(PrivProtField); // OK
// Console.WriteLine(PrivateField); // Error
}
}
Best Practices
- Fields: ใช้
privateเสมอ (Encapsulation) ให้เข้าถึงผ่าน Properties - Methods: ใช้
privateสำหรับ Helper,publicสำหรับ API - Base Class: ใช้
protectedสำหรับ Members ที่ Derived Class ต้องใช้ - Library: ใช้
internalสำหรับ Implementation Details