0. 目錄
1. 老版本的代碼
1 using System;
2 namespace csharp6
3 {
4 internal class Program
5 {
6 private static void Main(string[] args)
7 {
8 if (args==null)
9 {
10 throw new ArgumentNullException("args");
11 }
12 }
13 }
14 }
這段代碼並沒什么問題,運行良好。隨着時間的推移,有一天,我覺得args這個參數名不合適,想改一個更直觀的名字filePaths,表示我要接受一個文件路徑的數組。然后我們就直接把args這個名字給重構了,but,把 throw new ArgumentNullException("args"); 給忘了(resharper重構可能會同時重構這個名字),因為它僅僅是個字符串,書寫的時候容易拼錯,重構的時候也無法對它進行一個是否需要重構的分析,導致一些麻煩事情。
那么nameof運算符的目的就是來解決這個問題的。
2. nameof 運算符
nameof是C#6新增的一個關鍵字運算符,主要作用是方便獲取類型、成員和變量的簡單字符串名稱(非完全限定名),意義在於避免我們在代碼中寫下固定的一些字符串,這些固定的字符串在后續維護代碼時是一個很繁瑣的事情。比如上面的代碼改寫后:
1 using System;
2 namespace csharp6
3 {
4 internal class Program
5 {
6 private static void Main(string[] args)
7 {
8 if (args==null)
9 {
10 throw new ArgumentNullException(nameof(args));
11 }
12 }
13 }
14 }
我們把固定的 "args" 替換成等價的 nameof(args) 。按照慣例,貼出來兩種方式的代碼的IL。
"args"方式的IL代碼:
1 .method private hidebysig static void Main(string[] args) cil managed
2 {
3 .entrypoint
4 // Code size 22 (0x16)
5 .maxstack 2
6 .locals init ([0] bool V_0)
7 IL_0000: nop
8 IL_0001: ldarg.0
9 IL_0002: ldnull
10 IL_0003: ceq
11 IL_0005: stloc.0
12 IL_0006: ldloc.0
13 IL_0007: brfalse.s IL_0015
14 IL_0009: nop
15 IL_000a: ldstr "args"
16 IL_000f: newobj instance void [mscorlib]System.ArgumentNullException::.ctor(string)
17 IL_0014: throw
18 IL_0015: ret
19 } // end of method Program::Main
nameof(args)方式的IL代碼:
1 .method private hidebysig static void Main(string[] args) cil managed
2 {
3 .entrypoint
4 // Code size 22 (0x16)
5 .maxstack 2
6 .locals init ([0] bool V_0)
7 IL_0000: nop
8 IL_0001: ldarg.0
9 IL_0002: ldnull
10 IL_0003: ceq
11 IL_0005: stloc.0
12 IL_0006: ldloc.0
13 IL_0007: brfalse.s IL_0015
14 IL_0009: nop
15 IL_000a: ldstr "args"
16 IL_000f: newobj instance void [mscorlib]System.ArgumentNullException::.ctor(string)
17 IL_0014: throw
18 IL_0015: ret
19 } // end of method Program::Main
一樣一樣的,我是沒看出來有任何的差異,,,so,這個運算符也是一個編譯器層面提供的語法糖,編譯后就沒有nameof的影子了。
3. nameof 注意事項
nameof可以用於獲取具名表達式的當前名字的簡單字符串表示(非完全限定名)。注意當前名字這個限定,比如下面這個例子,你覺得會輸出什么結果?
1 using static System.Console;
2 using CC = System.ConsoleColor;
3
4 namespace csharp6
5 {
6 internal class Program
7 {
8 private static void Main()
9 {
10 WriteLine(nameof(CC));//CC
11 WriteLine(nameof(System.ConsoleColor));//ConsoleColor
12 }
13 }
14 }
第一個語句輸出"CC",因為它是當前的名字,雖然是指向System.ConsoleColor枚舉的別名,但是由於CC是當前的名字,那么nameof運算符的結果就是"CC"。
第二個語句輸出了"ConsoleColor",因為它是System.ConsoleColor的簡單字符串表示,而非取得它的完全限定名,如果想取得"System.ConsoleColor",那么請使用 typeof(System.ConsoleColor).FullName 。再比如微軟給的例子: nameof(person.Address.ZipCode) ,結果是"ZipCode"。
