반응형
nameof()
nameof 식은 변수, 형식 또는 멤버의 이름을 문자열 상수로 생성한다. nameof 식은 컴파일 타임에 계산되며 런타임에는 영향을 주지 않는다.
예제 코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Console.WriteLine(nameof(System.Collections.Generic)); // output: Generic | |
Console.WriteLine(nameof(List<int>)); // output: List | |
Console.WriteLine(nameof(List<int>.Count)); // output: Count | |
Console.WriteLine(nameof(List<int>.Add)); // output: Add | |
var numbers = new List<int> { 1, 2, 3 }; | |
Console.WriteLine(nameof(numbers)); // output: numbers | |
Console.WriteLine(nameof(numbers.Count)); // output: Count | |
Console.WriteLine(nameof(numbers.Add)); // output: Add |
nameof 식을 사용하여 인수 검사 코드를 더 쉽게 유지 관리할 수 있다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public string Name | |
{ | |
get => name; | |
set => name = value ?? throw new ArgumentNullException(nameof(value), $"{nameof(Name)} cannot be null"); | |
} |
nameof() vs ToString()의 차이점
ToString()은 런타임에서 평가된다. 그리고 포멧 변경이 가능하다.
nameof()은 컴파일 타임에서 평가된다. 그래서 런타임에서 영향을 받지 않는다.
'프로그래밍 > C#' 카테고리의 다른 글
예제로 복습하는 C# 쓰레드 생성 (27) | 2023.06.01 |
---|---|
읽기 / 쓰기 프로퍼티(Property) 선언 및 사용 방법 (54) | 2023.05.31 |
C# 명명된 인자(Named Arguments)와 선택적 인자(Optical Arguments) (20) | 2023.05.25 |
C# 스레딩 (25) | 2023.05.24 |
C# 컬렉션 - System.Collections.Hashtable (10) | 2023.05.23 |
댓글