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

interface에 속성을 선언할 수 있습니다. 다음 예제에서는 인터페이스 속성 접근자를 선언합니다.

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

일반적으로 인터페이스 속성에는 본문이 없습니다. 접근자는 속성이 읽기/쓰기인지, 읽기 전용인지, 쓰기 전용인지를 나타냅니다. 클래스 및 구조체와 달리, 접근자를 본문 없이 선언해도 자동 구현 속성이 선언되지 않습니다. 인터페이스는 멤버에 대한 기본 구현(속성 포함)을 정의할 수 있습니다. 인터페이스는 인스턴스 데이터 필드를 정의할 수 없으므로 인터페이스에서 속성에 대한 기본 구현을 정의하는 것은 드문 일입니다.

예제

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

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

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

앞의 예제에서는 명시적 인터페이스 구현을 보여 주었습니다. 예를 들어 Employee 클래스가 두 인터페이스 ICitizenIEmployee를 구현하고 두 인터페이스에 모두 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 => _name;
        set => _name = value;
    }

    private int _counter;
    public int Counter  // read-only instance property
    {
        get => _counter;
    }

    // constructor
    public Employee() => _counter = ++numberOfEmployees;
}
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);

샘플 출력

Enter number of employees: 210
Enter the name of the new employee: Hazem Abolrous
The employee information:
Employee number: 211
Employee name: Hazem Abolrous

참고 항목