>  기사  >  백엔드 개발  >  C#의 액세스 한정자

C#의 액세스 한정자

WBOY
WBOY원래의
2024-09-03 15:24:47590검색

이 문서에서는 C# 프로그래밍 언어 관점에서 개체 지향 프로그래밍의 가장 기본적인 개념을 다룹니다. 이 개념은 – 액세스 수정자(Access Modifiers)로 알려져 있습니다. 대답해야 할 첫 번째 질문은 – 액세스 수정자란 무엇입니까? 간단히 말해서 액세스 수정자는 코드의 어느 부분에서 어떤 개체/변수/상수/메서드(실질적으로 모든 것)에 액세스할 수 있는지 제어합니다. 액세스 수정자는 객체 지향 프로그래밍에서 추상화 개념을 증명하는 데 중요한 역할을 합니다. 이는 프로그램의 어떤 부분이 최종 사용자에게 표시되어야 하고 표시되지 않아야 하는지를 제어합니다. 물론 최종 사용자는 알고리즘에 포함된 상수와 변수에 대해 최소한의 관심을 갖습니다. 그는 출력을 얻기 위해 어떤 메소드를 호출해야 하는지에만 관심이 있습니다.

C#의 액세스 수정자 유형

C#은 네 가지 유형의 액세스 한정자를 제공합니다.

  • 비공개(열거형 및 인터페이스를 제외한 기본 액세스 한정자)
  • 보호됨(약간 제한됨)
  • 공개(제한 없음, 열거형 및 인터페이스에 대한 기본 선택)
  • 내부(동일 어셈블리 내 공개)

이 네 가지 액세스 수정자 외에도 두 가지 액세스 수준 조합이 더 있습니다.

  • 내부 보호
  • 개인정보 보호

예를 들어 각각을 이해해 보겠습니다.

1. 비공개

비공개는 가장 제한된 액세스 수준입니다. 또한 모든 상수, 변수, 사용자 정의 객체 등에 대한 기본 액세스 한정자이기도 합니다. 기본적으로 열거형과 인터페이스만 공개됩니다. 따라서 액세스 한정자를 지정하지 않으면 C#에서는 기본 한정자를 할당합니다.

개인 개체는 선언된 클래스, 구조체 또는 프로그램 섹션의 본문 외부에서 액세스할 수 없습니다. 개체가 선언된 본문 범위 외부에서 개체에 액세스하려고 하면 컴파일 시간 오류가 발생합니다.

예시 #1

using System;
class Employee //private by default
{
string name; //private by default
public string GetName()
{
return name;
}
public void SetName(string name)
{
this.name = name;
}
}
public class Program
{
public static void Main()
{
Employee emp = new Employee();
emp.SetName("John");
Console.Write("Employee name is " + emp.GetName());
// compile time error - 'Employee.name' is inaccessible due to its protection level
// Console.Write("Employee name is " + emp.name);
}
}

출력:

C#의 액세스 한정자

예시 #2

using System;
public class Program
{
public static void Main()
{
int x = 5; //private to the Main method, accessible inside nested code blocks in the Main method
if (true)
{
int y = 10; //private to the if block, not accessible outside if block
Console.WriteLine("x = " + x);
Console.WriteLine("y = " + y);
}
Console.WriteLine("x = " + x);
// compile-time error - The name 'y' does not exist in the current context.
// Console.WriteLine("y = " + y);
}
}

출력:

C#의 액세스 한정자

2. 보호됨

Protected 액세스 지정자는 클래스의 파생 인스턴스에서만 개체에 액세스할 수 있도록 제한합니다. 따라서 하위 클래스 객체가 상위 클래스의 보호 객체에 액세스하려고 하면 허용됩니다. 파생되지 않은 클래스는 모든 클래스의 보호된 멤버에 액세스할 수 없습니다. 물론, 보호된 객체는 자신이 속한 클래스의 메소드에 액세스할 수 있습니다.

예:

using System;
class Parent
{
protected string x;
public Parent()
{
x = "abc"; //accessible to own class methods
}
}
class Child : Parent // derived class
{
public static void Main()
{
var parentObj = new Parent();
var childObj = new Child();
Console.WriteLine(childObj.x); //accessible to derived class object instances
// compile-time error - Cannot access protected member 'Parent.x' via a qualifier of type 'Parent'; the qualifier must be of type 'Child' (or derived from it)
// Console.WriteLine(parentObj.x);
}
}

출력:

C#의 액세스 한정자

3. 공개

이것은 최소한으로 제한된 액세스 수정자입니다. 공용 객체는 실질적으로 전체 외부 세계에 액세스할 수 있으므로 허용 가능한 최고 액세스 수정자가 됩니다. 물론 이는 최소한의 보호 비용으로 인해 큰 비용이 발생합니다.

코드의 모든 부분에서 공개 멤버에 액세스할 수 있습니다. 이로 인해 보안이 가장 취약해집니다. 모든 코드 로직은 해당 값을 수정하여 예기치 않은 동작이 발생할 수 있습니다. 그러므로 어떤 물건을 공개하기 전에는 매우 신중해야 합니다.

비공개 액세스 수정자 예시에서 생성한 동일한 Employee 클래스에서 공개 액세스 수준을 변경하면 Getter 및 Setter 메서드가 필요하지 않습니다. 실제로 가장 좋은 방법은 개체를 비공개로 설정하고 C# Getter 및 Setter 속성을 사용하는 것입니다.

예:

using System;
class Employee
{
public string name;
}
public class Program
{
public static void Main()
{
Employee emp = new Employee();
emp.name = "John";
Console.Write("Employee name is " + emp.name);
}
}

출력:

C#의 액세스 한정자

4. 내부

내부 개체와 메서드는 동일한 어셈블리 내에서만 액세스할 수 있습니다. 이는 객체를 공개로 만들고 코딩 중인 프레임워크에만 해당 객체의 액세스를 제한하려는 경우 매우 유용한 액세스 수정자입니다.

따라서 본질적으로 모든 내부 개체는 동일한 어셈블리의 모든 영역에서 액세스할 수 있습니다.

이 작업을 이해하기 위해 두 개의 콘솔 애플리케이션을 만들어 보겠습니다.

예:

1단계: C# 콘솔 애플리케이션을 만들고 여기에 아래 코드를 삽입합니다.

using System;
namespace ConsoleApp1
{
public class Parent
{
internal int x;
public Parent()
{
x = 10;
}
}
public class Program
{
public static void Main()
{
var parentObj = new Parent();
// accessible within the same assembly
Console.Write("The value of x = " + parentObj.x);
}
}
}

2단계: bin 폴더에서 .dll 파일을 가져오는 솔루션을 빌드합니다.

C#의 액세스 한정자

3단계: 다른 콘솔 애플리케이션을 생성하고 ConsoleApp1에서 어셈블리 파일을 참조합니다. 아래 이미지에서 참조 추가를 클릭하고 2단계의 .dll 파일 위치를 찾아보세요. ~/ConsoleApp1/bin/Debug/ConsoleApp1.dll과 유사해야 합니다.

C#의 액세스 한정자

.dll 파일을 추가한 후 어셈블리에서 해당 파일을 찾아야 합니다.

C#의 액세스 한정자

Step4: Place the below code in ConsoleApp2.

using System;
using ConsoleApp1; //referencing the first assembly
namespace ConsoleApp2
{
class Program
{
static void Main(string[] args)
{
var parentObj = new Parent();
//not accessible outside the assembly
Console.Write(parentObj.x);
}
}
}

Step5: When you build ConsoleApp2, you will get a compile-time error indicating that ‘x’ from ConsoleApp1 cannot be accessed in other assemblies due to its protection level.

C#의 액세스 한정자

5. Protected Internal

This is a combination of both Protected and Internal access modifiers. An important concept to understand here is that Protected Internal means Protected OR Internal. It is a union of both access modifiers. It must never be thought to be an intersection.

So, Internal objects are not accessible outside the assembly, while Protected objects are accessible to any derived class in any assembly. What if I want to protect my object only in other assemblies and not in the same assembly? Simple solution – declare it as protected internal.

Example:

Step 1: Let us modify our ConsoleApp1 to reflect the code below. Notice we have changed the access level of our variable ‘x’ to protected internal.

using System;
namespace ConsoleApp1
{
public class Parent
{
protected internal int x;
public Parent()
{
x = 10;
}
}
public class Program
{
public static void Main()
{
var parentObj = new Parent();
// accessible within the same assembly
Console.Write("The value of x = " + parentObj.x);
}
}
}

Step 2: Build the solution again and replace the .dll in ConsoleApp2 with the updated one.

Step 3: Update the code in ConsoleApp2 as below:

using System;
using ConsoleApp1; //referencing the first assembly
namespace ConsoleApp2
{
class Program: Parent
{
static void Main(string[] args)
{
var progObj = new Program();
//accessible only via an object of the derived class.
Console.Write(progObj.x);
Console.Read();
}
}
}

Step 4: Run ConsoleApp2 to see the output.

C#의 액세스 한정자

6. Private Protected

This is a union combination of both Private and Protected access modifiers. Protected Internal means Protected OR Internal. So, Private objects are not accessible outside the code block in which it is declared, while Protected objects are accessible to any derived class in any assembly. What if I want to restrict my object’s access even in derived classes in other assemblies? Simple solution – declare it as protected internal.

Example:

Let us modify the access level of ‘x’ in ConsoleApp1 to Private Protected.

using System;
namespace ConsoleApp1
{
public class Parent
{
private protected int x;
public Parent()
{
x = 10;
}
}
public class Child: Parent {
public void DisplayX() {
// accessible only via derived class objects
Console.Write("Value of x = " + x);
}
}
public class Program
{
public static void Main()
{
var childObj = new Child();
childObj.DisplayX();
Console.Read();
}
}
}

Output:

C#의 액세스 한정자

Tabular Comparison

Following is a tabular comparison of Access Modifiers in C#:

Access Specifier Same Assembly Other Assembly
Same Class Derived Class Non-Derived Class Derived Class Non-Derived Class
Private Yes No No No No
Public Yes Yes Yes Yes Yes
Protected Yes Yes No Yes No
Internal Yes Yes Yes No No
Protected Internal Yes Yes Yes Yes No
Private Protected Yes Yes No No No

Conclusion

We have seen in the above article that access modifiers control the access of everything in the project. Various combinations of access levels cover the needs of various kinds of accessibility. The developers must choose wisely, keeping in mind the security and the absolute necessity of the object to be accessible in a certain block of code.

위 내용은 C#의 액세스 한정자의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:C#의 추상 클래스다음 기사:C#의 추상 클래스