식 본문 멤버 (식으로 이루어지는 멤버)

2021. 1. 24. 12:42개발/C#

 

using System;

using System.Collections.Generic;

namespace testproject

{

  class Program

  {

    static void Main(string[] args)

    {

      // 메서드를 비롯하여 속성(인덱서), 생성자, 종료자는 공통된 특징이 있다.

      // 이들은 모두 클래스의 멤버이며, 본문이 중괄호 {}로 만들어져 있다.

     

      // 이런 멤버의 본문을 식으로만 구현하는 것이 가능하다

      // 이렇게 식으로 구현된 멤버를 "Expression-Bodied Member"라고하고, 우리말로 "식 본문 멤버"라고 한다.

      // 멤버 => 식;  -> 이와 같이 사용한다

    }

  }

  class FriendList

  {

    private List<string> list = new List<string>();

    //public FriendList() => Console.WriteLine("FriendList()");   // 생성자

    //~FriendList() => Console.WriteLine("~FriendList()");        // 종료자

    public void Add(string name) => list.Add(name);             // list.Add() 메서드를 호출하는 식

    public void Remove(string name) => list.Remove(name);       // list.Remove() 메서드를 호출하는 식

    // public int Capacity => list.Capacity;                       // 읽기 전용 프로퍼티

    // public string this[int index] => list[index];               // 읽기 전용 인덱서

    public int Capacity1                                           // 프로퍼티

    {

      get => list.Capacity;

      set => list.Capacity = value;

    }

    public string this[int index]                                  // 인덱서

    {

      get => list[index];

      set => list[index] = value;

    }

  }

}