Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

폐관수련

[C#] 인터페이스 (interface) 본문

Programming/grammar

[C#] 인터페이스 (interface)

믜믜 2021. 12. 29. 00:49

인터페이스란

인터페이스는 메서드만으로 이루어진 추상 클래스라고 정의할 수 있다.

 

public interface IMyInterface	// 관례적으로 인터페이스명은 I 접두사를 붙임
{
    // 0개 이상 메서드 선언 (비어 있는 인터페이스를 정의할 수 있음)
    void MyMethod();
}

 

메서드만으로 이루어진 추상 클래스와의 차이점

 

  • 클래스는 다중 상속이 불가능하지만 인터페이스는 다중 상속이 가능
  • 클래스 상속과 인터페이스의 상속이 동시에 가능
  • override 예약어가 필요 없음

 

특징

자식 클래스에서의 호출

class MyClass : IMyInterface
{
    // 인터페이스명을 직접 붙이지 않는 경우, 반드시 public 접근 제한자를 명시
    public void MyMethod() { }
    
    // 인터페이스명을 직접 붙이는 경우, public 접근 제한자를 생략할 수 있음
    // public 접근 제한자가 생략되었을 뿐 private는 아니다
    // void IMyInterface.MyMethod() { }
}

MyClass myClass = new MyClass();
myClass.MyMethod();


// 접근 제한자를 생략하고 인터페이스명을 붙이는 경우, 반드시 형변환해야 호출 가능
// 명시적으로 인터페이스의 멤버에 종속시킨다고 표시하기 때문
// IMyInterface myInterface = myClass as IMyInterface;
// myInterface.MyMethod();

 

프로퍼티 포함 가능

(C# 프로퍼티는 내부적으로 메서드로 구현되기 때문)

interface MyInterface
{
    void MyMethod();
    int Count { get; set; }
    string Name { get; }
}

 

다형성

class FirstClass : IMyInterface
{
    public void MyMethod() { Console.WriteLine("First Class"); }
}

class SecondClass : IMyInterface
{
    public void MyMethod() { Console.WriteLine("Second Class"); }
}

 

'Programming > grammar' 카테고리의 다른 글

[C#] Func, Action  (0) 2021.11.04
정규 표현식  (0) 2021.08.11
리스트 컴프리헨션 (List Comprehension)  (0) 2021.08.11
[C#] ControlPaint.DrawReversibleFrame  (0) 2020.07.23
[C#] List / Array / ArrayList  (0) 2020.07.20
Comments