Unity 내일배움캠프 TIL 1026 | C# 접근 제한자

cheeseonrose·2023년 10월 26일
0

Unity 내일배움캠프

목록 보기
64/89
post-thumbnail

💡 C# 접근 제한자

🐧 정의

  • 외부로부터 타입 혹은 그 타입 멤버들로의 접근을 제한할 때 사용하는 것
  • 클래스나 구조체와 같은 Type 앞에 사용하거나 메서드, 속성, 필드 등의 클래스 및 구조체 멤버 앞에 사용

🦉 요약표

호출자의 위치publicprotected internalprotectedinternalprivate protectedprivate
클래스 내
파생 클래스 (동일 어셈블리)
비파생 클래스 (동일 어셈블리)
파생 클래스 (다른 어셈블리)
비파생 클래스 (다른 어셈블리)

🦜 어셈블리(Assembly)

  • 하나의 실행 파일 영역을 의미
  • 실행 파일(.exe) 또는 동적 연결 라이브러리(.dll) 파일의 형태를 가지며, .NET 애플리케이션의 구성 요소이다.

🦆 C#에서 기본 접근 제한자

  • namespace 안에서는 internal이, Class 안에서는 private이 기본 접근 제한자이다.

🦢 Class와 Struct의 접근 제한자 차이

  • Class는 6가지의 접근 제한자를 가질 수 있다.
    (public, internal, private, protected, protected internal, private protected)
  • Struct는 상속이 불가능하기 때문에 3가지의 접근 제한자를 가질 수 있다.
    (public, internal, private)

🐦 protected internal

  • 동일 어셈블리 내에 있다면 모두 접근할 수 있다.
  • 다른 어셈블리 내에 있을 경우, 해당 클래스의 파생 클래스에서 접근할 수 있다.
  • 외부 프로젝트에서 dll을 참조하여 상속 받는 경우 사용한다.
    • DLL(Dynamic Link Library) : 동적 링크 라이브러리의 약자로, 표준화 된 함수나 데이터를 모아놓은 것을 의미
// Assembly1.cs
// Compile with: /target:library
public class BaseClass
{
   protected internal int myValue = 0;
}

class TestAccess
{
    void Access()
    {
        var baseObject = new BaseClass();
        baseObject.myValue = 5;
    }
}
// Assembly2.cs
// Compile with: /reference:Assembly1.dll
class DerivedClass : BaseClass
{
    static void Main()
    {
        var baseObject = new BaseClass();
        var derivedObject = new DerivedClass();

        // Error CS1540, because myValue can only be accessed by
        // classes derived from BaseClass.
        // baseObject.myValue = 10;

        // OK, because this class derives from BaseClass.
        derivedObject.myValue = 10;
    }
}

출처 - Microsoft 액세스 한정자(C# 프로그래밍 가이드)
출처 - Microsoft protected internal(C# 참조)
출처 - C# 접근 제한자
출처 - protected internal과 internal의 차이



끗~!

0개의 댓글