运算式nameof
可以取得变数/常数、命名空间、类型或成员的名称作为字串表示形式:
static void Main(string[] args){ var name = "Bill"; var age = 18; 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 Console.WriteLine(nameof(name)); // output: name Console.WriteLine(nameof(age)); // output: age}
在型别与命名空间的情况下,产生的名称通常是不完整的,以上述範例为例,System.Collections.Generic
命名空间,会显示Generic
: