산업 제조
산업용 사물 인터넷 | 산업자재 | 장비 유지 보수 및 수리 | 산업 프로그래밍 |
home  MfgRobots >> 산업 제조 >  >> Industrial programming >> C 언어

C# 액세스 수정자

C# 액세스 수정자

이 자습서에서는 예제를 통해 C#의 public, private, protected 및 내부 액세스 수정자에 대해 알아봅니다.

C#에서 액세스 한정자는 형식(클래스, 인터페이스 등) 및 형식 멤버(필드, 메서드 등)의 액세스 가능성을 지정합니다. 예를 들어,

class Student {

  public string name;
    
  private int num;

  }

여기,

액세스 수정자의 유형

C#에는 4가지 기본 유형의 액세스 한정자가 있습니다.

<시간>

1. 공개 액세스 수정자

유형 또는 유형 멤버를 선언할 때 public , 어디서나 액세스할 수 있습니다. 예를 들어,

using System;

namespace MyApplication {

  class Student {
    public string name = "Sheeran";
      
    public void print() {
      Console.WriteLine("Hello from Student class");
     }
  }

  class Program {
    static void Main(string[] args) {
    
      // creating object of Student class
      Student student1 = new Student();
      
      // accessing name field and printing it
      Console.WriteLine("Name: " + student1.name);

      // accessing print method from Student
      student1.print();
      Console.ReadLine();
    }
  }
}

출력

Name: Sheeran
Hello from Student class

위의 예에서 Student라는 클래스를 만들었습니다. name 필드 포함 및 메소드 print() .

// accessing name field and printing it
Console.WriteLine("Name: " + student1.name);

// accessing print method from Student
student1.print();

필드와 메서드가 공개되어 있으므로 프로그램에서 액세스할 수 있습니다. 수업.

참고 :student1 개체를 사용했습니다. 학생 멤버에 액세스할 수 있는 클래스입니다. 자세한 내용은 C# 클래스 및 개체를 참조하세요. .

<시간>

2. 개인 액세스 수정자

private을 사용하여 유형 멤버를 선언할 때 액세스 수정자, 동일한 class 내에서만 액세스할 수 있습니다. 또는 struct . 예를 들어,

using System;

namespace MyApplication {

  class Student {
    private string name = "Sheeran";
      
    private void print() {
      Console.WriteLine("Hello from Student class");
     }
  }

  class Program {
    static void Main(string[] args) {
    
      // creating object of Student class
      Student student1 = new Student();
      
      // accessing name field and printing it
      Console.WriteLine("Name: " + student1.name);

      // accessing print method from Student
      student1.print();

      Console.ReadLine();
    }
  }
}

위의 예에서 Student라는 클래스를 만들었습니다. name 필드 포함 및 메소드 print() .

// accessing name field and printing it
Console.WriteLine("Name: " + student1.name);

// accessing print method from Student
student1.print();

필드와 메서드는 비공개이므로 프로그램에서 액세스할 수 없습니다. 수업. 여기에서 코드는 다음 오류를 생성합니다.

Error    CS0122    'Student.name' is inaccessible due to its protection level    
Error    CS0122    'Student.print()' is inaccessible due to its protection level    
<시간>

3. 보호된 액세스 수정자

유형 멤버를 protected로 선언할 때 , 동일한 클래스와 파생 클래스에서만 액세스할 수 있습니다. 예를 들어,

using System;

namespace MyApplication {

  class Student {
    protected string name = "Sheeran";
  }

  class Program {
    static void Main(string[] args) {
    
      // creating object of student class
      Student student1 = new Student();
      
      // accessing name field and printing it
      Console.WriteLine("Name: " + student1.name);
      Console.ReadLine();
    }
  }
}

위의 예에서 Student라는 클래스를 만들었습니다. name 필드 포함 . 필드가 보호되어 있으므로 프로그램에서 액세스할 수 없습니다. 수업.

여기에서 코드는 다음 오류를 생성합니다.

Error    CS0122    'Student.name' is inaccessible due to its protection level    

이제 protected에 액세스해 보겠습니다. 파생 클래스의 멤버입니다.

using System;

namespace MyApplication {

  class Student {
    protected string name = "Sheeran";
  }
  
  // derived class
  class Program : Student {
    static void Main(string[] args) {

      // creating object of derived class
      Program program = new Program();
      
      // accessing name field and printing it
      Console.WriteLine("Name: " + program.name);
      Console.ReadLine();
    }
  }
}

출력

Name: Sheeran

위의 예에서 우리는 Student 클래스를 생성했습니다. 보호 필드 name 포함 . Program을 상속받았음을 주목하세요. 학생의 클래스 수업.

// accessing name field and printing it
Console.WriteLine("Name: " + program.name);

protected 이후 멤버는 파생 클래스에서 액세스할 수 있으며 name에 액세스할 수 있습니다. 프로그램에서 수업.

<시간>

4. 내부 액세스 수정자

유형 또는 유형 멤버를 internal로 선언할 때 , 동일한 어셈블리 내에서만 액세스할 수 있습니다.

어셈블리는 유형(클래스, 인터페이스 등)과 리소스(데이터)의 모음입니다. 이들은 함께 작동하고 논리적 기능 단위를 형성하도록 구축되었습니다.

이것이 어셈블리를 실행할 때 어셈블리 내의 모든 클래스와 인터페이스가 함께 실행되는 이유입니다. 자세히 알아보려면 C# 어셈블리를 방문하세요.

<시간>

예:동일한 어셈블리 내의 내부

using System;

namespace Assembly {

  class Student {
   internal string name = "Sheeran";
  }

  class Program {
    static void Main(string[] args) {
    
      // creating object of Student class
      Student theStudent = new Student();
      
      // accessing name field and printing it
      Console.WriteLine("Name: " + theStudent.name);
      Console.ReadLine();
    }
  }
}

출력

Name: Sheeran

위의 예에서 Student라는 클래스를 만들었습니다. name 필드 포함 . 필드가 internal이므로 , 프로그램에서 액세스할 수 있습니다. 같은 어셈블리에 있는 클래스입니다.

internal을 사용하는 경우 단일 어셈블리 내에서 public처럼 작동합니다. 액세스 수정자.

<시간>

예:다른 어셈블리의 내부

먼저 하나의 어셈블리를 만들어 보겠습니다.

// Code on Assembly1
using System;

namespace Assembly1 {

  public class StudentName {
    internal string name = "Sheeran";
  }

  class Program {
    static void Main(string[] args) {
    }
  }
}

여기에서 이 코드는 Assembly1에 있습니다. . 내부 필드 name을(를) 만들었습니다. StudentName 클래스 내부 . 이제 이 필드는 동일한 어셈블리 Assembly1에서만 액세스할 수 있습니다. .

이제 다른 어셈블리를 만들어 보겠습니다.

// Code on Assembly2
using System;

// access Assembly1
using Assembly1;

namespace Assembly2 {
  class Program {
    static void Main(string[] args) {
      StudentName student = new StudentName();

      // accessing name field from Assembly1
      Console.Write(student.name);
      Console.ReadLine();
     }
  }
}

여기에서 이 코드는 Assembly2에 있습니다. . name에 액세스하려고 합니다. StudentName 필드 클래스(어셈블리1 ).

Assembly1의 필드에 액세스하려면 , 먼저 Assembly1의 참조를 설정해야 합니다. 어셈블리2에서 . 이제 코드

using Assembly1;

Assembly1의 코드를 사용할 수 있습니다. 조립2에 .

여기서 name에 액세스하려고 할 때 Assembly2의 필드 , 오류가 발생합니다.

Error    CS0122    'StudentName.name' is inaccessible due to its protection level

name 때문입니다. Assembly1에 있는 내부 필드입니다. .

<시간>

5. 보호된 내부 액세스 수정자

protected internal protected의 조합입니다. 및 internal 액세스 수정자.

protected internal 멤버를 선언할 때 , 동일한 어셈블리에서 액세스할 수 있고 다른 어셈블리에서 포함하는 클래스의 파생 클래스에 액세스할 수 있습니다.

// Code on Assembly1
using System;

namespace Assembly1 {
  public class Greet {
    protected internal string msg="Hello";
  }

  class Program {
    static void Main(string[] args) {
      Greet greet = new Greet();
      Console.WriteLine(greet.msg);
      Console.ReadLine();
     }
  }
}

출력

Hello

위의 코드는 Assembly1에 있습니다. .

위의 예에서 우리는 Greet라는 클래스를 생성했습니다. msg 필드 포함 . 필드는 내부적으로 보호되므로 프로그램에서 액세스할 수 있습니다. 같은 어셈블리에 있는 클래스입니다.

Greet에서 클래스를 파생시키자 다른 어셈블리에서 보호된 내부 필드 msg에 액세스하려고 시도합니다. 그것에서.

// Code on Assembly2
using System;

// access Assembly1
using Assembly1;

namespace Assembly2 {

  // derived class of Greet
  class Program: Greet {
    static void Main(string[] args) {
      Program greet = new Program();

      // accessing name field from Assembly1
      Console.Write(greet.msg);
      Console.ReadLine();
    }
  }
}

출력

Hello

위의 코드는 Assembly2에 있습니다. .

위의 예에서 우리는 Program을 상속받았습니다. 인사의 클래스 클래스(Assembly1에서 ).

// accessing name field from Assembly1
Console.Write(greet.msg);

msg에 액세스할 수 있습니다. 인사 Assembly1 클래스 Assembly2에서 .

msg 때문입니다. 보호된 내부 필드이며 Greet의 자식 클래스에서 액세스하려고 합니다. .

<시간>

6. 개인 보호 액세스 수정자

private protected 액세스 수정자는 private의 조합입니다. 및 protected . C# 버전 7.2 이상에서 사용할 수 있습니다.

private protected 멤버를 선언할 때 , 동일한 클래스 내에서만 액세스할 수 있고 동일한 어셈블리 내에서 파생된 클래스에만 액세스할 수 있습니다. 예를 들어,

// Code in Assembly1
using System;

namespace Assembly1 {
  public class StudentName {
    private protected string name = "Sheeran";
  }

  //derived class of StudentName class
  class Program1 : StudentName {

    static void Main(string[] args) {

      Program1 student = new Program1();

      //  accessing name field from base class
      Console.Write(student.name);
      Console.ReadLine();
    }
  }
}

출력

Sheeran

위의 코드는 Assembly1에 있습니다.

위의 예에서는 StudentName 클래스를 생성했습니다. private protected 필드 이름 .

Program1을 상속받았습니다. StudentName의 클래스 수업.

private protected 이후 멤버는 동일한 어셈블리 내의 파생 클래스에서 액세스할 수 있으며 name에 액세스할 수 있습니다. 프로그램1에서 수업.

StudentName에서 클래스를 파생해 보겠습니다. 다른 어셈블리에서 개인 보호 필드 name에 액세스하려고 시도합니다. 이것으로부터. 예를 들어,

// Code in Assembly2
using System;
//access Assembly1
using Assembly1;

namespace Assembly2 {

  //derived class of StudentName
  class Program : StudentName {
    static void Main(string[] args) {
      Program student = new Program();
    
      // accessing name field from Assembly1
      Console.Write(student.name);
      Console.ReadLine();
     }
  }
}

위의 코드는 Assembly2에 있습니다.

위의 예에서 name에 액세스하려고 할 때 StudentName 파생 클래스의 필드 , 오류가 발생합니다.

Error    CS0122    'StudentName.name' is inaccessible due to its protection level    

이름 때문입니다. 필드가 Assembly1에 있음 파생 클래스는 Assembly2에 있습니다. .

참고 :유형(클래스, 인터페이스 등)과 함께 액세스 수정자를 사용할 수도 있습니다. 그러나 public 및 internal 액세스 수정자가 있는 유형만 사용할 수 있습니다.


C 언어

  1. C# 클래스 및 개체
  2. C# 정적 키워드
  3. C# 추상 클래스 및 메서드
  4. C# 중첩 클래스
  5. C# 부분 클래스 및 부분 메서드
  6. C# 봉인된 클래스 및 메서드
  7. C++ 클래스 템플릿
  8. C 스토리지 클래스
  9. Java - 수정자 유형
  10. C++의 다형성