내용 보기
작성자
관리자 (IP : 106.247.248.10)
날짜
2022-12-21 09:31
제목
[C#] [스크랩] C# 7.2 - readonly 구조체
|
값 타입(struct) readonly 인스턴스의 경우 "defensive copy"와 같은 C# 컴파일러의 노력을 통해 값을 변경할 수 없게 만들었다는 것을 설명했는데요. 반면, 지난번 예제에서 봤듯이 "defensive copy"는 의도치 않은 부작용을 낳습니다. 그 이외에도 "defensive copy"는 숨겨진 코드로 인한 값 복사로 메서드 및 공용 속성을 접근할 때 성능 저하가 발생하는 문제도 있습니다. class Program
{
readonly StructPerson sarah = new StructPerson() { Name = "Kerrigan", Age = 27 };
static void Main(string[] args)
{
Program pg = new Program();
pg.Test();
}
private void Test()
{
sarah.IncAge();
}
}
struct StructPerson
{
public int Age;
public string Name;
public void IncAge()
{
Age++;
}
}
readonly struct StructPerson
{
public int Age; // 컴파일 에러: CS8340 Instance fields of readonly structs must be readonly.
public string Name; // 컴파일 에러: CS8340 Instance fields of readonly structs must be readonly.
public void IncAge()
{
Age++;
}
}
readonly struct StructPerson { public readonly int Age; public readonly string Name; public void IncAge() { Age++; } }
readonly struct StructPerson { public readonly int Age; public readonly string Name; public StructPerson(string name, int age) { Name = name; Age = age; } public StructPerson IncAge() { return new StructPerson(this.Name, this.Age + 1); } }
class Program
{
readonly StructPerson sarah = new StructPerson("Kerrigan", 27);
static void Main(string[] args)
{
Program pg = new Program();
pg.Test();
}
private void Test()
{
sarah.IncAge();
/*
일반 구조체의 경우 IncAge 메서드 호출은 다음과 같은 코드로 바뀌지만,
StructPerson temp = sarah;
temp.IncAge();
*/
}
}
C# 7.2부터, 불변(immutable) 객체를 만들 때는 readonly 구조체를 사용한다!
또한 대개의 경우 struct는 불변 객체로 만들지 않을 이유가 없으므로 가능한 struct는 모두 readonly 구조체로 만든다!
|
출처1
https://www.sysnet.pe.kr/2/0/11524
출처2