본문 바로가기
개발/기타

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

by 유다110 2016. 6. 7.
반응형

* 인터페이스(Interface)

0. 인터페이스는 특정한 클래스를 만들 때 사용하는 규약이다.

1. 인터페이스 상속하기

class Program

{

class Dummy : IDisposable //IDisposable 인터페이스를 상속하고 이를 구현했을 때,

{

public void Dispose()

{

throw new NotImplementedException(); //자동으로 구현되는 부분. 이 부분을 알맞게 바꿔 코딩한다.

Console.WriteLine("Dispose() 메서드를 호출합니다.");

}

}

static void Main(string[] args)

{

Dummy dummy = new Dummy();

dummy.Dispose();

//혹은 위 두 문장을

using(Dummy dummy = new Dummy())

{

}

//이렇게 using 블록을 사용해주면 using 블록을 벗어날 때 자동으로 Dispose() 메서드를 호출한다.

}

}


* 인터페이스 생성

0. 인터페이스는 클래스와 동급의 카테고리이다. 즉, 클래스를 생성하는 위치라면 어디든지 만들 수 있다.

1. 인터페이스를 생성할 땐 interface 키워드를 사용한다.

interface [인터페이스 이름]{}

2. 보통 인터페이스는 클래스 내부에서 생성하지 않고 다른 파일에 생성해서 사용한다.



* 인터페이스 멤버

0. 인터페이스 생성

interface IBasic

{

int TestInstanceMethod();

int TestProperty{get; set;}


}


1. 인터페이스 상속

class Program

{

class TestClass : IBasic

{

}

}


2. 인터페이스 구현

class Program

{

class TestClass : IBasic

{

public int TestInstanceMethod()

{

throw new NotImplementedException();

}


public int TestProperty

{

get

{

throw new NotImplementedException();

}

set

{

throw new NotImplementedException();

}

}

}

}

3. 다형성 구현 가능(다중 상속 구현) : 하나의 클래스가 여러 부모 클래스를 가질 수 있다.

static void Main(string[] args)

{

IBasic basic = new TestClass();

}

>> 하나의 클래스가 여러 부모 클래스를 가질 수 있다.

class Child : Parent, IDisposable, IComparable

{

public void Dispose()

{

throw new NotImplementedException();

}

public int CompareTo(object obj)

{

throw new NotImplementedException();

}

}

* 인터페이스 사용 시 주의사항

0. 여러 개의 인터페이스 상속으로 인해 구현해야 하는 메서드 이름이 겹칠 때는 <인터페이스>.<메서드 이름>() 형태로 구분해서 구현

반응형

'개발 > 기타' 카테고리의 다른 글

[Github] SSH key 등록 및 커밋  (0) 2016.11.07
[C#] 델리게이터(delegate)와 람다(lambda)  (1) 2016.06.09
[C#] 제네릭(Generic)과 구조체(Struct)  (0) 2016.06.05
[C#] 상속과 다형성  (0) 2016.06.05
[C#] 클래스 기본  (0) 2016.06.05

댓글