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

ขอบเขตของตัวแปร Internal ใน C#

คีย์เวิร์ด internal ใน C# กำหนดให้สมาชิกเข้าถึงได้ ภายใน Assembly เดียวกันเท่านั้น (Assembly = .dll หรือ .exe ที่คอมไพล์รวมกัน) ไม่สามารถเข้าถึงจาก Assembly อื่นที่ Reference มาได้

ขอบเขต (Scope) ของ internal

  • ภายในคลาสเดียวกัน: ได้
  • คลาสอื่นใน Assembly เดียวกัน: ได้
  • คลาสลูกใน Assembly เดียวกัน: ได้
  • คลาสใน Assembly อื่น (Reference มา): ไม่ได้

ตัวอย่าง

using System;

namespace RectangleApplication
{
    class Rectangle
    {
        // Internal fields - เข้าถึงได้ใน Assembly นี้เท่านั้น
        internal double length;
        internal double width;
        
        // Internal method
        internal double GetArea() => length * width;
        
        public void Display()
        {
            Console.WriteLine($"ความยาว: {length}");
            Console.WriteLine($"ความกว้าง: {width}");
            Console.WriteLine($"พื้นที่: {GetArea()}");
        }
    }
    
    class ExecuteRectangle
    {
        static void Main(string[] args)
        {
            Rectangle r = new Rectangle();
            r.length = 4.5;    // เข้าถึงได้ - ใน Assembly เดียวกัน
            r.width = 3.5;
            r.Display();
            Console.ReadLine();
        }
    }
}

ผลลัพธ์

ความยาว: 4.5
ความกว้าง: 3.5
พื้นที่: 15.75

Internal vs Public vs Private

ModifierSame ClassSame AssemblyOther Assembly
private✓✗✗
internal✓✓✗
public✓✓✓

การใช้งานจริง

  • ซ่อน Implementation Details ภายใน Library/Assembly
  • ใช้กับ Helper Classes, Internal Services, DTOs ที่ไม่ต้อง Expose
  • internal class - คลาสทั้งหมดเข้าถึงได้ใน Assembly เดียว
  • รวมกับ protected ได้: protected internal (Assembly OR Derived), private protected (Assembly AND Derived)

Tip: ใช้ [InternalsVisibleTo("FriendAssembly")] Attribute อนุญาต Assembly อื่นเข้าถึง Internal Members ได้ (สำหรับ Unit Test)