interface(C# 참조)

업데이트: 2007년 11월

인터페이스에는 메서드, 속성, 이벤트 또는 인덱서의 시그니처만 포함됩니다. 멤버는 다음 예제에서와 같이 인터페이스를 구현하는 클래스나 구조체에서 구현됩니다.

예제

interface ISampleInterface
{
    void SampleMethod();
}

class ImplementationClass : ISampleInterface
{
    // Explicit interface member implementation: 
    void ISampleInterface.SampleMethod()
    {
        // Method implementation.
    }

    static void Main()
    {
        // Declare an interface instance.
        ISampleInterface obj = new ImplementationClass();

        // Call the member.
        obj.SampleMethod();
    }
}

인터페이스는 네임스페이스 또는 클래스의 멤버가 될 수 있으며 다음 멤버의 시그니처를 포함할 수 있습니다.

인터페이스는 하나 이상의 기본 인터페이스에서 상속할 수 있습니다.

기본 형식 목록에 기본 클래스와 인터페이스가 있는 경우 기본 클래스가 목록의 처음에 있어야 합니다.

인터페이스를 구현하는 클래스는 해당 인터페이스의 멤버를 명시적으로 구현할 수 있습니다. 명시적으로 구현된 멤버는 클래스 인스턴스를 통해 액세스할 수 없고 인터페이스의 인스턴스를 통해서만 액세스할 수 있습니다.

명시적 인터페이스 구현에 대한 자세한 내용과 코드 예제는 명시적 인터페이스 구현(C# 프로그래밍 가이드)을 참조하십시오.

다음 예제에서는 인터페이스 구현 방법을 보여 줍니다. 이 예제에서 인터페이스에는 속성 선언이 포함되고 클래스에는 구현이 포함됩니다.

interface IPoint
{
   // Property signatures:
   int x
   {
      get;
      set;
   }

   int y
   {
      get;
      set;
   }
}

class Point : IPoint
{
   // Fields:
   private int _x;
   private int _y;

   // Constructor:
   public Point(int x, int y)
   {
      _x = x;
      _y = y;
   }

   // Property implementation:
   public int x
   {
      get
      {
         return _x;
      }

      set
      {
         _x = value;
      }
   }

   public int y
   {
      get
      {
         return _y;
      }
      set
      {
         _y = value;
      }
   }
}

class MainClass
{
   static void PrintPoint(IPoint p)
   {
      Console.WriteLine("x={0}, y={1}", p.x, p.y);
   }

   static void Main()
   {
      Point p = new Point(2, 3);
      Console.Write("My Point: ");
      PrintPoint(p);
   }
}
// Output: My Point: x=2, y=3

C# 언어 사양

자세한 내용은 C# 언어 사양의 다음 단원을 참조하십시오.

  • 1.9 인터페이스

  • 3.4.5 인터페이스 멤버

  • 4.2.4 인터페이스 형식

  • 10.1.2.2 인터페이스 구현

  • 11.2 구조체 인터페이스

  • 13 인터페이스

참고 항목

개념

C# 프로그래밍 가이드

참조

C# 키워드

참조 형식(C# 참조)

속성 사용(C# 프로그래밍 가이드)

인덱서 사용(C# 프로그래밍 가이드)

class(C# 참조)

struct(C# 참조)

기타 리소스

C# 참조