Interface IControl
{
void Paint()
}
Interface ITextBox : IControl
{
void SetText(string text)
}
class TextBox : ITextBox
{
public void Paint(){...}
public void SetText(){...}
}
Interface 특징
- 개체 생성이 불가능하고 , 참조만 가능!
- 암시적으로 public , virtual.
- interface는 상수, 필드 , 연산자 , 생성자 , 소멸자 , 형식 및 static 멤버도 포함할 수 없다.
- method , property , event 및 indexer를 포함.
- interface의 구현은 상속한 class나 structure에서 한다.
=> 동일 인터페이스 상속 시 내부 구현 내용이 다르더라도 동일 이름의 사양을 가지게됨.- 이름은 관습적으로 I로 시작 : ex) IName
- Interface를 구현하는 class 또는 structure는 interface의 상위 interface까지 구현.
Interface 목적
- 계약 (contract) : 상속한 class와 structure는 interface에 정의한 사양을 구현.
- 추상화 (abstraction) : 구현 내용은 감추고 멤버의 사양만 노출.
- 약한 결합 (loose coupling) : 개체에 종속하지 않도록 함
- 다중 상속 (multiple inheritance)
명시적 Interface
class나 structure가 동일한 signature method를 가진 interface를 둘 이상 상속 시 충돌을 피하기 위해 interface 출처와 함께 표시하여 구현.
- 암시적으로 public이며 접근 제한자 설정 불가능.
- abstract , virtual , override , new를 붙이지 못한다.
- 개체를 통해 직접 호출이 안되고 , 반드시 해당 Interface로 캐스팅하여 호출.
namespace PR01 { interface IA { void F(); void G(); } interface IB { void F(); void K(); } class AB : IA, IB { public void F() { Console.WriteLine("IA.F()"); } public void G() { Console.WriteLine("IA.G()"); } public void K() { Console.WriteLine("IB.K()"); } void IB.F() { Console.WriteLine("IB.F()"); } // 명시적 인터페이스 구현 } internal class Program { static void Main(string[] args) { AB ab = new AB(); ab.F(); // IA.F() 호출 (ab as IB).F(); // IB로 캐스팅 후 IB.F() 호출 } } }
public interface IComparable
{
int CompareTo(object o);
}
- Array.Sort(배열) 메소드는 Array의 각 요소의 IComparable 구현을 사용하여 1차원 Arr 전체 요소 정렬.
=> 이는 이미 int,long,string 등의 Bulit-in type의 배열은 이미 IComparable이 구현되어 있으므로 , Array.Sort() 메소드는 Quick Sort 알고리즘으로 오름차순 정렬.
class Student : IComparable<Student>
{
public int Age
{ get { return Age; }
set { this.Age = value;}
}
public string Name { get; set; }
public int CompareTo(Student s)
{
return this.Age.CompareTo(s.Age);
}
}
internal class Program
{
static void Main(string[] args)
{
Student[] stArr = new Student[]
{
new Student {Age = 23, Name = "Paul" },
new Student {Age = 20, Name = "John" },
new Student {Age = 22, Name = "Ringo" },
new Student {Age = 21, Name = "George" }
};
Array.Sort(stArr);
}
}
}
class Student
{
public int Age
{ get { return Age; }
set { this.Age = value;}
}
}
class AgeAscending : IComparer<Student>
{
public int Compare(Student x, Student y)
{
return x.Age.CompareTo(y.Age);
}
}
internal class Program
{
static void Main(string[] args)
{
Student[] stArr = new Student[]
{
new Student {Age = 23},
new Student {Age = 20 },
new Student {Age = 22 },
new Student {Age = 21 }
};
Array.Sort(stArr,new AgeAscending());
}
}