Interface type
Peponi │ 11/26/2024 │ 3m
C#
SyntaxTypeinterface
Interface type
11/26/2024
3m
Peponi
C#
SyntaxTypeinterface
1. Introduction
Interface에는 class와 struct가 구현해야 할 멤버가 선언되어 있다. interface
는 공통된 접근으로 다형성을 갖출 수 있게 하며 또다른 interface
로부터 상속받아 추가적인 확장을 할 수 있다. 선언된 멤버에 대한 기본 구현을 제공할 수 있고 (C# 8), static abstract
멤버를 통해 공통된 구현을 할 수도 있다. (C# 11)
2. interface 기본 정의 및 사용
interface
는 아래와 같이 정의하고 사용한다.
internal interface IPrintable
{
void Print(string message);
}
internal class ConsoleWriter : IPrintable
{
public void Print(string message) => Console.WriteLine(message);
}
2.1. interface 상속
다음과 같은 방법으로 interface
간 상속이 가능하다.
internal interface IBase
{
void Print(string message);
}
internal interface IDerived : IBase
{
void PrintDerived(string message);
}
internal class InterfaceDerived : IDerived
{
public void Print(string message) => Console.WriteLine("IBase.Print");
public void PrintDerived(string message) => Console.WriteLine("IDerived.Print");
}
2.2. interface 기본 구현 제공 (C# 8)
C# 8 버전부터 아래와 같은 방법으로 interface
의 기본 구현을 제공할 수 있다. C# 7.3 등 하위 버전에서 기본 구현을 시도할 경우 CS8370
및 CS8701
에러가 발생한다.
internal interface IPrintable
{
void PrintConsole(string message) => Console.WriteLine(message);
}
internal class PrintClass : IPrintable {}
IPrintable printClass = new PrintClass();
printClass.PrintConsole("print");
2.3. 멤버에 대한 한정자 허용 (C# 8)
C# 8 버전부터 다음과 같은 한정자를 interface
멤버에 사용할 수 있다.
private
protected
internal
public
virtual
abstract
sealed
static
extern
partial
internal interface IPrintable
{
static void PrintConsole(string message) => Console.WriteLine(message);
}
IPrintable.PrintConsole("print");
2.4. static abstract 멤버 제공 (C# 11)
C# 11버전부터 아래와 같은 방법으로 static abstract
멤버를 제공할 수 있다. 해당 기능을 통해 상속받은 class
또는 struct
의 정적 멤버 구현을 요구할 수 있다.
internal interface IPrintable
{
static abstract void PrintConsole(string message);
}
internal class PrintClass : IPrintable
{
public static void PrintConsole(string message) => Console.WriteLine(message);
}
PrintClass.PrintConsole("AAA");