>  기사  >  백엔드 개발  >  C#으로 보호됨

C#으로 보호됨

PHPz
PHPz원래의
2024-09-03 15:28:471018검색

이 글에서는 C#에서 protected를 어떻게 구현할 수 있는지 자세히 살펴보겠습니다. 액세스 수정자의 도움으로 매개변수와 클래스의 접근성 수준을 제한할 수 있습니다. C#에는 다음과 같은 액세스 한정자가 있습니다

  • 공개
  • 비공개
  • 보호됨
  • 내부

C#의 보호된 수정자

C#에서는 protected 수정자를 사용하여 액세스가 포함 유형으로 제한되도록 지정할 수 있습니다. 또한 포함 클래스에서 파생된 유형에도 사용할 수 있습니다. 보호라는 단어는 자체 및 파생 클래스에서 액세스할 수 있거나 볼 수 있음을 의미합니다.

이 멤버 또는 유형의 도움으로 동일한 클래스에서 사용되거나 파생 클래스에서 사용되는 코드로만 액세스할 수 있습니다. protected 키워드는 private과 public 수정자 사이에 있습니다. 이는 개인 수정자와 거의 동일하지만 멤버가 파생 클래스에 액세스할 수 있도록 허용합니다. 우리는 부모에게 자녀의 속성에 대한 액세스 권한을 부여하려고 할 때 주로 protected 키워드를 사용합니다. 따라서 보호된 키워드를 사용하여 논리를 재사용할 수 있습니다.

예:

using System;
class Test
{
protected int _x; private int _y;
}
class Test1 : Test
{
public Test1 ()
{
// In this we can  access the variable protected int but we cannot access private int variable
Console.WriteLine(this._x);
}
}
class Program
{
static void Main()
{ Test1 b = new Test1 (); }
}

Test와 Test1이라는 2개의 클래스를 생각해 보세요. Test1 클래스는 Test에서 파생됩니다. Test 클래스 내부를 살펴보면 두 개의 int 필드가 선언된 것을 볼 수 있습니다. 1개는 보호되고 1개는 비공개입니다.

클래스 B Test1에서는 protected int에 액세스할 수 있지만 private int에는 액세스할 수 없습니다. 따라서 protected 수정자는 파생 클래스에 대한 추가 액세스를 제공합니다. 따라서 protected 키워드를 사용하면 모든 파생 클래스가 포함된 보호 필드에 액세스할 수 있습니다.

클래스도 보호할 수 있습니다. 다음은 이를 선언하는 방법의 예시입니다

구문:

public class Test
{
protected class Child
{
}
}

중첩 클래스에서만 보호 클래스로 선언할 수 있습니다. 네임스페이스 내부에서는 정의할 수 없습니다.

C#에서 Protected를 구현하는 예

다음은 C#에서 protected를 구현하는 방법을 보여주는 예입니다.

예제 #1 – 하위 클래스를 구현하지 않은 경우

코드:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProtectedExample
{
class demo
{
// String Variable declared as protected
protected string name;
public void print()
{
Console.WriteLine("\name is " + name);
}
}
class Program
{
static void Main(string[] args)     // main method
{
demo d = new demo();
Console.Write("Enter your name:\t");
d.name = Console.ReadLine();
d.print();
Console.ReadLine();
}
}
}

위의 예에서는 문자열이 protected로 선언되었습니다. protected가 다른 클래스로부터 해당 멤버를 숨기기 때문에 이 프로그램은 오류를 발생시킵니다. 그래서 어린이반에서만 접근이 가능합니다.

예제 #2 – 상속을 이용한 구현

코드:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProtectedExample
{
class Demo
{
protected string name = "Protected Keyword";
protected void Display(string val)
{
Console.WriteLine("This is " + val);
}
}
class Program : Demo   // inheritance
{
static void Main(string[] args)
{
Program program = new Program();
// Accessing protected variable
Console.WriteLine("This is " + program.name);
// Accessing protected function
program.Display("protected example");
Console.ReadLine();
}
}
}

위의 예에서 Parent 클래스는 보호된 멤버로 구성됩니다. Protected는 문자열을 선언하는 데 사용됩니다. 이제 하위 클래스는 상위 클래스에서 파생되며 상속 개념을 사용하여 보호된 멤버에 액세스합니다.

출력:

C#으로 보호됨

예시 #3

코드:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProtectedExample
{
class Parent
{
private String Private = "My name is John";    // string declared as private
protected String Protected = "My name is Dan"; //  string declared as protected
}
class Child : Parent // inheritance
{
public void Show()
{
Console.WriteLine(Protected);
}
}
class Program
{
static int Main(string[] args)  // main method
{
Child child = new Child();    // child object
child.Show();
Console.ReadKey();
return 0;
}
}
}

위의 예에서 상위 클래스에는 비공개 및 보호 문자열이 포함되어 있습니다. 하위 클래스는 상위 클래스에서 파생됩니다. Show()는 private에 접근할 수 없지만 protected에 접근할 수 있습니다. 하위 클래스 개체는 메서드를 호출하는 데 사용됩니다. Protected는 클래스 외부에서 멤버가 접근하지 못하도록 보호하는 데 사용됩니다.

출력:

C#으로 보호됨

생성자를 보호됨으로 선언할 수도 있습니다. 따라서 생성자를 보호됨으로 선언하면 하위 클래스에서 호출할 수 있습니다.

구문:

public class TEst : Test1
{
public Test() : base() // here we can Call the protected base constructor
{
}
}

보호된 메서드를 호출할 수 없습니다. 파생 클래스에서 보호된 생성자를 호출할 수 있습니다.

보호된 내부 접근 수정자

protected Internal의 도움으로 액세스가 포함 클래스에서 파생된 현재 유형으로 제한되도록 지정할 수 있습니다. 따라서 동일한 클래스의 코드나 다른 어셈블리에 작성된 파생 클래스에서 멤버 및 유형에 액세스할 수 있습니다.

예:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProtectedExample
{
class Demo
{
protected internal string name;    // variable is declared as protected internal
public void print()
{
Console.WriteLine("name is " + name);
}
}
class Program
{
static void Main(string[] args) // main method
{
Demo d = new Demo();
Console.Write("Enter your name:\t");
// Accepting value in protected internal variable
d.name = Console.ReadLine();
d.print();
Console.ReadLine();
}
}
}

출력:

C#으로 보호됨

C#에서 Protected의 중요성

Protected 키워드는 동일한 클래스에서 사용되는 코드로 이러한 유형의 변수에 액세스할 수 있기 때문에 유용합니다. 상위 클래스 멤버에 접근할 수 있도록 하위 클래스에 권한을 부여하고 싶을 때 유용합니다. 그래서 그런 의미에서 코드 재사용성을 확보하는 것이 중요합니다.

결론

따라서 변수로 보호를 사용하고 상속 개념을 사용하여 변수에 액세스할 수 있습니다. 클래스 자체 또는 하위 클래스에서 멤버에 액세스할 수 있는 경우에 사용할 수 있습니다.

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

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