인터페이스 내부에는 클래스 내부에 넣을 수 있었던 인스턴트 메서드, 속성을 넣을 수 있습니다.
예제를 살펴보면서 알아보겠습니다.
// 인터페이스 생성
interface IBasic
{
int TestInstanceMethod(); // 메서드에 내부 구현할 수 없습니다.
int TestProperty { get; set; } // 속성도 마찬가지로 내부 구현할 수 없습니다.
}
class Program
{
class TestClass : IBasic
{
}
static void Main(string[] args)
{
}
}
이제 인터페이스를 구현하기 위해서 ( Ctrl + . ) 단축키를 눌러줍니다.
다음 IBasic 인터페이스 구현을 눌러주면 됩니다.
그러면 아래와 같이 자동으로 내부 코드가 생성됩니다. 이후에는 생성된 코드에 내부 코드를 입력하면 됩니다.
class TestClass : IBasic
{
// throw 부분들은 클래스에서 이후에 구현해주면 됩니다.
public int TestInstanceMethod()
{
throw new NotImplementedException();
}
public int TestProperty
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
이제 인터페이스의 다중 상속에 대해서 알아보겠습니다.
아래의 코드를 보고 다시 설명을 드리겠습니다.
class Program
{
class Parent { }
// 한개의 클래스와 두개의 인터페이스를 상속 받습니다.
class Child : Parent, IDispoable, IComparable
{
// IDispoable 인터페이스 구현
public void Dispose()
{
throw new NotImplementedException();
}
// IComparable 인터페이스 구현
public int CompareTo(object obj)
{
throw new NotImplementedException();
}
}
static void Main(string[] args)
{
// 이렇게 상속받으면 다음과 같이 세 종류로 자료형 변환이 가능해집니다.
Child child = new Child();
Parent childAsParent = new Child();
IDisposable childAsDisposable = new Child();
IComparable childAsComparable = new Child();
}
}
'C# > 프로그래밍 고급' 카테고리의 다른 글
C# 프로그래밍 고급 - 06. 델리게이터 (0) | 2024.05.30 |
---|---|
C# 프로그래밍 고급 - 05. 예외 객체 (0) | 2024.05.30 |
C# 프로그래밍 고급 - 04. 예외처리 (1) | 2024.05.29 |
C# 프로그래밍 고급 - 02. 인터페이스 생성 (0) | 2024.05.29 |
C# 프로그래밍 고급 - 01. 인터페이스 (1) | 2024.05.29 |