Software/Tools

[C#] Interface

charom 2010. 6. 15. 07:02
reference : Apress Illustrated CSharp 2008

Implementing Interfaces with Duplicate Members

중첩 멤버 함수의 구현.

두 인터페이스는 똑 같이 PrintOut이라는 method를 가지고 있다.
여기까지는 OK, 문제는 AB클래스는 이 두 Interface를 상속하게된다.
클래스나 struct는 interface를 implement해야 한다. 그럼 어떻게 각 각 두 인터페이스에 맞게 구현할 수 있나? 정답은 공통의 기능을 만족하는 한 method만 implement해 주면 된다.

References to Multiple Interfaces
main에서는 세가지로 Class AB의 PrintOut을 호출할 수 있다.
interface I1{void PrintOut(string s);}
interface I2{void PrintOut(string s);}

class AB : I1,I2{
  public void PrintOut(string s)
  {
    Console.WriteLine("Call : {0}",s);
  }
}
class Program {
  static void Main() {
     AB ab = new AB();
     I1 i1 = (I1) ab; // Get ref to I1
     I2 i2 = (I2) ab; // Get ref to I2
     ab.PrintOut("object."); // Call through class object
     i1.PrintOut("interface 1."); // Call through I1
     i2.PrintOut("interface 2."); // Call through I2
   }
}

명시적 인터페이스 멤버 구현
다음과 같이 명시적으로 다르게 멤버를 구현 할수 있다.
class AB:I1,I2{
   void I1.PrintOut(string s){..}
   void I2.PrintOut(string s){...}
}
구조는 다음과 같다.


Class의 Member와 Interface의 멤버 구현.
다음 code는 어떻게 되는가?

interface IIfc1 { void PrintOut(string s); }
class MyBaseClass // Declare base class.
{
   public void PrintOut(string s) // Declare the method.
   {
     Console.WriteLine("Calling through: {0}", s);
   }
}
class Derived : MyBaseClass, IIfc1 // Declare class.
{
   //nothing
}

class Program {
   static void Main()
   {
      Derived d = new Derived(); // Create class object
      d.PrintOut("object."); // Call method
   }
}
위 code의 구조는 다음 그림과 같다.

Interfaces Can Inherit Interfaces 인터페스의 인터페이스 상속