Share via


인터페이스 속성(C# 프로그래밍 가이드)

업데이트: 2007년 11월

interface(C# 참조)에서 속성을 선언할 수 있습니다. 다음은 인터페이스 인덱서 접근자의 예제입니다.

public interface ISampleInterface
{
    // Property declaration:
    string Name
    {
        get;
        set;
    }
}

인터페이스 속성의 접근자에는 본문이 없습니다. 접근자를 사용하는 목적은 속성이 읽기/쓰기, 읽기 전용 또는 쓰기 전용인지 여부를 나타내는 것입니다.

예제

다음 예제의 IEmployee 인터페이스에는 읽기/쓰기 속성인 Name과 읽기 전용 속성인 Counter가 있습니다. Employee 클래스는 IEmployee 인터페이스를 구현하고 이 두 속성을 사용합니다. 프로그램에서는 새 직원 이름과 현재 번호를 읽어 들이고 직원 이름과 계산된 직원 번호를 표시합니다.

멤버가 선언된 인터페이스를 참조하는 속성의 정규화된 이름을 사용할 수 있습니다. 예를 들면 다음과 같습니다.

string IEmployee.Name
{
    get { return "Employee Name"; }
    set { }
}

이를 명시적 인터페이스 구현(C# 프로그래밍 가이드)이라고 합니다. 예를 들어, Employee 클래스가ICitizen 및 IEmployee라는 두 개의 인터페이스를 구현하며 두 인터페이스 모두에 Name 속성이 있는 경우 해당 인터페이스 멤버를 명시적으로 구현해야 합니다. 예를 들면 다음과 같습니다.

string IEmployee.Name
{
    get { return "Employee Name"; }
    set { }
}

위 선언에서는 IEmployee 인터페이스의 Name 속성을 구현합니다.

string ICitizen.Name
{
    get { return "Citizen Name"; }
    set { }
}

그러나 이와 같이 선언하면 ICitizen 인터페이스의 Name 속성을 구현합니다.

interface IEmployee
{
    string Name
    {
        get;
        set;
    }

    int Counter
    {
        get;
    }
}

public class Employee : IEmployee
{
    public static int numberOfEmployees;

    private string name;
    public string Name  // read-write instance property
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }

    private int counter;
    public int Counter  // read-only instance property
    {
        get
        {
            return counter;
        }
    }

    public Employee()  // constructor
    {
        counter = ++counter + numberOfEmployees;
    }
}

class TestEmployee
{
    static void Main()
    {
        System.Console.Write("Enter number of employees: ");
        Employee.numberOfEmployees = int.Parse(System.Console.ReadLine());

        Employee e1 = new Employee();
        System.Console.Write("Enter the name of the new employee: ");
        e1.Name = System.Console.ReadLine();

        System.Console.WriteLine("The employee information:");
        System.Console.WriteLine("Employee number: {0}", e1.Counter);
        System.Console.WriteLine("Employee name: {0}", e1.Name);
    }
}
210
Hazem Abolrous

샘플 출력

Enter number of employees: 210

Enter the name of the new employee: Hazem Abolrous

The employee information:

Employee number: 211

Employee name: Hazem Abolrous

참고 항목

개념

C# 프로그래밍 가이드

참조

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

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

속성 및 인덱서 비교(C# 프로그래밍 가이드)

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

인터페이스(C# 프로그래밍 가이드)