인터페이스 멤버를 명시적으로 구현하는 방법(C# 프로그래밍 가이드)
이 예제에서는 interfaceIDimensions
및 Box
클래스를 선언합니다. 이 클래스는 인터페이스 멤버 GetLength
및 GetWidth
를 명시적으로 구현합니다. 멤버는 인터페이스 인스턴스 dimensions
를 통해 액세스합니다.
예시
interface IDimensions
{
float GetLength();
float GetWidth();
}
class Box : IDimensions
{
float lengthInches;
float widthInches;
Box(float length, float width)
{
lengthInches = length;
widthInches = width;
}
// Explicit interface member implementation:
float IDimensions.GetLength()
{
return lengthInches;
}
// Explicit interface member implementation:
float IDimensions.GetWidth()
{
return widthInches;
}
static void Main()
{
// Declare a class instance box1:
Box box1 = new Box(30.0f, 20.0f);
// Declare an interface instance dimensions:
IDimensions dimensions = box1;
// The following commented lines would produce compilation
// errors because they try to access an explicitly implemented
// interface member from a class instance:
//System.Console.WriteLine("Length: {0}", box1.GetLength());
//System.Console.WriteLine("Width: {0}", box1.GetWidth());
// Print out the dimensions of the box by calling the methods
// from an instance of the interface:
System.Console.WriteLine("Length: {0}", dimensions.GetLength());
System.Console.WriteLine("Width: {0}", dimensions.GetWidth());
}
}
/* Output:
Length: 30
Width: 20
*/
강력한 프로그래밍
Main
메서드의 다음 줄은 컴파일 오류를 생성하므로 주석으로 처리되었습니다. 명시적으로 구현된 인터페이스 멤버는 class 인스턴스에서 액세스할 수 없습니다.//System.Console.WriteLine("Length: {0}", box1.GetLength()); //System.Console.WriteLine("Width: {0}", box1.GetWidth());
또한
Main
메서드의 다음 줄은 메서드가 인터페이스 인스턴스에서 호출되기 때문에 상자 크기를 성공적으로 출력합니다.System.Console.WriteLine("Length: {0}", dimensions.GetLength()); System.Console.WriteLine("Width: {0}", dimensions.GetWidth());
참고 항목
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET