Programming/C#
[Programming/C#] 식으로 이루어지는 멤버 (Member => Expression)
scii
2020. 9. 24. 17:41
메소드를 비롯하여 속성, 인덱서, 생성자, 소멸자는 공통된 특징이 있다. 이들은 모두 클래스의 멤버로서 본문이 중괄호{}로 만들어져 있다. 이러한 멤버의 본문을 식(expression)만으로 구현하는 것이 가능하다.
이렇게 구현된 멤버를 영어로 "Expression-Bodied Memeber" 라고 하고, "식 본문 멤버" 라고 한다. 문법은 다음과 같다.
멤버 => 식;
아래는 읽기 전용 속성과 인덱서를 식으로 구현하는 방법이다. 읽기 전용으로만 사용한다고 가정하면 get 키워드조차 생략할 수 있다.
class Foo
{
public int Capacity => list.Capacity;
public string this[int index] => list[index];
}
허나 읽기/쓰기 모두 가능한 속성 또는 인덱서를 구현하려면 get, set 키워드를 명시적으로 기술해줘야 한다.
class Foo
{
public int Capacity
{
get => list.Capacity;
set => list.Capacity = value;
}
public string this[int index]
{
get => list[index];
set => list[index] = value;
}
}
expression bodied member 예제
using System;
using System.Collections.Generic;
namespace test
{
class FriendList
{
private List<string> list = new List<string>();
public void Add(string name) => list.Add(name);
public void Remove(string name) => list.Remove(name);
public void PrintAll()
{
foreach (var s in list)
Console.WriteLine(s);
}
public FriendList() => Console.WriteLine("FriendList()");
~FriendList() => Console.WriteLine("~Friend()");
// 읽기 전용 프로퍼티
// public int Capacity => list.Capacity;
public int Capacity
{
get => list.Capacity;
set => list.Capacity = value;
}
// 일기 전용 인덱서
// public string this[int index] => list[index];
public string this[int index]
{
get => list[index];
set => list[index] = value;
}
}
internal class Program
{
public static void Main(string[] args)
{
FriendList obj = new FriendList();
obj.Add("c#");
obj.Add("c++");
obj.Add("java");
obj.Remove("java");
obj.PrintAll();
Console.WriteLine($"{obj.Capacity}");
obj.Capacity = 10;
Console.WriteLine($"{obj.Capacity}");
Console.WriteLine($"{obj[0]}");
obj[0] = "c++++";
obj.PrintAll();
}
}
}
/* 결과
FriendList()
c#
c++
4
10
c#
c++++
c++
~Friend()
*/