Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Local Inner Class (Nested Class) trong C#

Nested class: Class khai báo bên trong class khác. Có quyền truy cập member của outer class (nếu static thì chỉ truy cập static member).

Ví dụ

class One
{
    public int num1;
    public class Two
    {
        public int num2;
    }
}

class Demo
{
    static void Main()
    {
        One x = new One();
        x.num1++;
        
        One.Two xy = new One.Two();
        xy.num2++;
    }
}

Đặc điểm:

  • Class Two là nested class bên trong One
  • Dùng One.Two để truy cập từ bên ngoài
  • Nested class có thể private, protected, internal, public
  • Non-static nested class (instance) có thể truy cập instance member của outer class qua instance outer

Static Nested Class

class Outer
{
    static int staticField = 10;
    int instanceField = 20;
    
    static class Nested
    {
        public void Access()
        {
            Console.WriteLine(staticField); // OK
            // Console.WriteLine(instanceField); // Lỗi - cần instance Outer
        }
    }
}

Use case: Encapsulation, helper class chỉ dùng trong outer class, implement interface privately.