이 예제에서는 인터페이스IDimensions
멤버 GetLength
GetWidth
를 명시적으로 구현하는 인터페이스 및 클래스Box
를 선언합니다. 멤버는 인터페이스 인스턴스 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(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:
//Console.WriteLine($"Length: {box1.GetLength()}");
//Console.WriteLine($"Width: {box1.GetWidth()}");
// Print out the dimensions of the box by calling the methods
// from an instance of the interface:
Console.WriteLine($"Length: {dimensions.GetLength()}");
Console.WriteLine($"Width: {dimensions.GetWidth()}");
}
}
/* Output:
Length: 30
Width: 20
*/
강력한 프로그래밍
메서드에서
Main
다음 줄은 컴파일 오류를 생성하기 때문에 주석 처리됩니다. 명시적으로 구현된 인터페이스 멤버는 클래스 인스턴스에서 액세스할 수 없습니다.//Console.WriteLine($"Length: {box1.GetLength()}"); //Console.WriteLine($"Width: {box1.GetWidth()}");
또한
Main
메서드에서 인터페이스 인스턴스에서 메서드를 호출하기 때문에 다음 줄이 상자의 차원을 성공적으로 출력합니다.Console.WriteLine($"Length: {dimensions.GetLength()}"); Console.WriteLine($"Width: {dimensions.GetWidth()}");
참고하십시오
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
.NET