interface(C# 참조)
Programming/C# / 2010. 9. 14. 16:53
인터페이스에는 메서드, 대리자 또는 이벤트의 시그니처만 포함됩니다. 메서드는 다음 예제에서와 같이 인터페이스를 구현하는 클래스에서 구현됩니다.
interface ISampleInterface
{
void SampleMethod();
}
class ImplementationClass : ISampleInterface
{
// Explicit interface member implementation:
void ISampleInterface.SampleMethod()
{
// Method implementation.
}
static void Main()
{
// Declare an interface instance.
ISampleInterface obj = new ImplementationClass();
// Call the member.
obj.SampleMethod();
}
}
설명
인터페이스는 네임스페이스 또는 클래스의 멤버가 될 수 있으며 다음 멤버의 시그니처를 포함할 수 있습니다.
인터페이스는 하나 이상의 기본 인터페이스에서 상속할 수 있습니다.
기본 형식 목록에 기본 클래스와 인터페이스가 있는 경우 기본 클래스가 목록의 처음에 있어야 합니다.
인터페이스를 구현하는 클래스는 해당 인터페이스의 멤버를 명시적으로 구현할 수 있습니다. 명시적으로 구현된 멤버는 클래스 인스턴스를 통해 액세스할 수 없고 인터페이스의 인스턴스를 통해서만 액세스할 수 있습니다. 예를 들면 다음과 같습니다.
명시적 인터페이스 구현에 대한 자세한 내용과 코드 예제는 명시적 인터페이스 구현(C# 프로그래밍 가이드)을 참조하십시오.
예제
다음 예제에서는 인터페이스 구현 방법을 보여 줍니다. 이 예제에서 IPoint 인터페이스에는 필드 값을 설정하고 가져오는 것을 담당하는 속성 선언이 있습니다. Point 클래스에는 속성 구현이 있습니다.
// keyword_interface_2.cs
// Interface implementation
using System;
interface IPoint
{
// Property signatures:
int x
{
get;
set;
}
int y
{
get;
set;
}
}
class Point : IPoint
{
// Fields:
private int _x;
private int _y;
// Constructor:
public Point(int x, int y)
{
_x = x;
_y = y;
}
// Property implementation:
public int x
{
get
{
return _x;
}
set
{
_x = value;
}
}
public int y
{
get
{
return _y;
}
set
{
_y = value;
}
}
}
class MainClass
{
static void PrintPoint(IPoint p)
{
Console.WriteLine("x={0}, y={1}", p.x, p.y);
}
static void Main()
{
Point p = new Point(2, 3);
Console.Write("My Point: ");
PrintPoint(p);
}
}
출력
My Point: x=2, y=3
출처 : http://msdn.microsoft.com/ko-kr/library/87d83y5b(v=VS.80).aspx
반응형
'Programming > C#' 카테고리의 다른 글
| 배열 초기화 및 카피 - C ( memset , memcpy) (0) | 2010.09.15 |
|---|---|
| C#에서 다중 상속 비슷한 기능이 필요할 때.. (0) | 2010.09.15 |
| abstract(C# 참조) (0) | 2010.09.14 |
| 이벤트 만들기 (초보자) (0) | 2010.09.14 |
| STL map == C# Dictionary (0) | 2010.09.13 |
