성장일기 : 문과생의 개발 여정 (งᐖ)ว ( ᐛ )و

C# 접근제한자 본문

카테고리 없음

C# 접근제한자

hyemi_flora 2024. 3. 29. 15:10

접근제한자는 외부로부터 타입(클래스, 구조체, 인터페이스, 델리게이트 등) 혹은 그 타입 멤버들(메서드, 속성, 이벤트, 필드 등)로의 접근을 제한할 때 사용하는 것

접근제한자는 상황에 따라 다른 디폴트값을 갖는다.
클래스 안에서 멤버들에 대해서는 private이 디폴트, namespace 안에서 클래스는 internal이 디폴트

public 모든 외부(파생클래스 포함)에서 이 타입(Type: 클래스, 구조체, 인터페이스, 델리게이트 등)을 엑세스할 수 있다. (개별 타입 멤버의 엑세스 권한은 해당 멤버의 접근 제한자에 따라 별도로 제한될 수 있다)
internal 동일한 Assembly 내에 있는 다른 타입들이 엑세스 할 수 있다. 하지만, 다른 어셈블리에서는 접근이 불가하다.
protected 파생클래스에서 이 클래스 멤버를 엑세스할 수 있다.
private 동일 클래스/구조체 내의 멤버만 접근 가능하다.

 

1. public: 해당 멤버를 어디서든 접근가능.

public class MyPublicClass {
    public int MyPublicField;
    public void MyPublicMethod() { }
}

2. private: 해당 멤버는 같은 클래스 내에서만 접근할 수 있다.

public class MyprivateClass {
    private int myPrivateField;
    private void MyPrivateMethod() { }
}

3. protected: 해당 멤버는 같은 클래스 또는 파생 클래스 내에서만 접근할 수 있다.

public class MyBaseClass {
    protected int myProtectedField;
    protected void MyProtectedMethod() { }
}
public class MyDerivedClass : MyBaseClass {
    public void SomeMethod() {
        // myProtectedField 및 MyProtectedMethod에 접근 가능
        myProtectedField = 10;
        MyProtectedMethod();
    }
}

4. internal: 해당 멤버는 동일한 어셈블리 내에서만 접근 가능. 다른 어셈블리에서는 접근할 수 없다.
(.NET프레임 워크에서는 하나의 실행파일 영역을 어셈블리라는 영역으로 부른다고 한다.)

internal class MyInternalClass {
    internal int MyInternalField;
    internal void MyInternalMethod() { }
}

5. protected internal: 해당 멤버는 같은 어셈블리 내에서는 어디서든 접근할 수 있다. 파생 클래스에서도 접근 가능.

public class MyBaseClass {
    protected internal int myProtectedInternalField;
    protected internal void MyProtectedInternalMethod() { }
}
public class MyDerivedClass : MyBaseClass {
    public void SomeMethod() {
        // myProtectedInternalField 및 MyProtectedInternalMethod에 접근 가능
        myProtectedInternalField = 10;
        MyProtectedInternalMethod();
    }
}

6. private protected: 해당 멤버는 같은 어셈블리 내에서 파생 클래스 내에서만 접근할 수 있다. 다른 어셈블리에서는 접근불가능.

public class MyBaseClass {
    private protected int myPrivateProtectedField;
    private protected void MyPrivateProtectedMethod() { }
}
public class MyDerivedClass : MyBaseClass {
    public void SomeMethod() {
        // myPrivateProtectedField 및 MyPrivateProtectedMethod에 접근 가능
        myPrivateProtectedField = 10;
        MyPrivateProtectedMethod();
    }
}