protected
키워드는 멤버 액세스 한정자입니다.
비고
이 페이지에서는 protected
접근에 대해 다룹니다.
protected
키워드는 protected internal
및 private protected
액세스 한정자의 일부이기도 합니다.
보호된 멤버는 해당 클래스 및 파생 클래스 인스턴스에서 액세스할 수 있습니다.
다른 액세스 한정자와 비교 protected
하려면 접근성 수준을 참조하세요.
예제 1
기본 클래스의 보호된 멤버는 파생 클래스 형식을 통해 액세스가 발생하는 경우에만 파생 클래스에서 액세스할 수 있습니다. 예를 들어 다음 코드 세그먼트를 고려합니다.
namespace Example1
{
class BaseClass
{
protected int myValue = 123;
}
class DerivedClass : BaseClass
{
static void Main()
{
var baseObject = new BaseClass();
var derivedObject = new DerivedClass();
// Error CS1540, because myValue can only be accessed through
// the derived class type, not through the base class type.
// baseObject.myValue = 10;
// OK, because this class derives from BaseClass.
derivedObject.myValue = 10;
}
}
}
이 문 baseObject.myValue = 10
은 기본 클래스 참조(baseObject
형식 BaseClass
)를 통해 보호된 멤버에 액세스하기 때문에 오류를 생성합니다. 보호된 멤버는 파생 클래스 형식 또는 파생된 형식을 통해서만 액세스할 수 있습니다.
protected
액세스 한정자와 달리 private protected
모든 어셈블리의 파생 클래스에서 액세스할 수 있습니다. 달리 protected internal
, 동일한 어셈블리 내에서 파생되지 않은 클래스의 액세스를 허용하지 않습니다 .
구조체를 상속할 수 없으므로 구조체 멤버를 보호할 수 없습니다.
예제 2
이 예제에서 클래스 DerivedPoint
는 .에서 Point
파생됩니다. 따라서 파생 클래스에서 직접 기본 클래스의 보호된 멤버에 액세스할 수 있습니다.
namespace Example2
{
class Point
{
protected int x;
protected int y;
}
class DerivedPoint: Point
{
static void Main()
{
var dpoint = new DerivedPoint();
// Direct access to protected members.
dpoint.x = 10;
dpoint.y = 15;
Console.WriteLine($"x = {dpoint.x}, y = {dpoint.y}");
}
}
// Output: x = 10, y = 15
}
액세스 수준을 x
으로 y
변경하면 컴파일러에서 오류 메시지를 실행합니다.
'Point.y' is inaccessible due to its protection level.
'Point.x' is inaccessible due to its protection level.
어셈블리 간 액세스
다음 예제에서는 멤버가 protected
다른 어셈블리에 있는 경우에도 파생 클래스에서 액세스할 수 있음을 보여 줍니다.
// Assembly1.cs
// Compile with: /target:library
namespace Assembly1
{
public class BaseClass
{
protected int myValue = 0;
}
}
// Assembly2.cs
// Compile with: /reference:Assembly1.dll
namespace Assembly2
{
using Assembly1;
class DerivedClass : BaseClass
{
void Access()
{
// OK, because protected members are accessible from
// derived classes in any assembly
myValue = 10;
}
}
}
이 크로스 어셈블리 접근성은 private protected
이(가) 동일한 어셈블리에 대한 액세스를 제한하는 것과는 구별되며, protected internal
와 유사하지만, protected internal
는 파생되지 않은 클래스의 경우에도 동일한 어셈블리 내에서 액세스를 허용한다는 점이 있습니다.
C# 언어 사양
자세한 내용은 C# 언어 사양에서 선언된 접근성을 참조하세요. 언어 사양은 C# 구문 및 사용의 최종 소스입니다.
참고하십시오
.NET