個人の備忘録です。
結論
- nameof演算子に変数名、型、メンバー、メソッド名などの識別子を与えると、同等の文字列を得られる
- 文字列を指定する場面でnameofを使うことで、コードの修正漏れを防ぎ保守性の高いコードにすることができる
- nameof演算子はコンパイル時に評価され、実行時には影響を与えない
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は式なので指定した変数名やメソッド名が正しいかどうかコンパイル時にチェックされる
例
switch (property.Name)
{
case nameof(Model.Field1): // 修正などされて一致しなくなればエラーが出る
case nameof(Model.Field2): // 修正などされて一致しなくなればエラーが出る
Console.WriteLine("hoge");
break;
default:
break;
}