C#基礎知識之nameof
阿新 • • 發佈:2022-03-08
nameof
表示式可生成變數、型別或成員的名稱作為字串常量。
一、 舊程式碼
using System; namespace csharp6 { internal class Program { private static void Main(string[] args) { if (args==null) { throw new ArgumentNullException("args"); } } } }
這段程式碼並沒什麼問題,執行良好。隨著時間的推移,有一天,我覺得args這個引數名不合適,想改一個更直觀的名字filePaths,表示我要接受一個檔案路徑的陣列。然後我們就直接把args這個名字給重構了,但是把
throw new ArgumentNullException("args");
給忘了,因為它僅僅是個字串,書寫的時候容易拼錯,重構的時候也無法對它進行一個是否需要重構的分析,導致一些麻煩事情。那麼nameof運算子的目的就是來解決這個問題的。
二、nameof 運算子
nameof是C#6新增的一個關鍵字運算子,主要作用是方便獲取型別、成員和變數的簡單字串名稱(非完全限定名),意義在於避免我們在程式碼中寫下固定的一些字串,這些固定的字串在後續維護程式碼時是一個很繁瑣的事情。比如上面的程式碼改寫後:
using System; namespace csharp6 { internal class Program { private static void Main(string[] args) { if (args==null) { throw new ArgumentNullException(nameof(args)); } } } }
我們把固定的 "args" 替換成等價的 nameof(args) 。按照慣例,貼出來兩種方式的程式碼的IL。
"args"方式的IL程式碼:
.method private hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 22 (0x16) .maxstack 2 .locals init ([0] bool V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldnull IL_0003: ceq IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0015 IL_0009: nop IL_000a: ldstr "args" IL_000f: newobj instance void [mscorlib]System.ArgumentNullException::.ctor(string) IL_0014: throw IL_0015: ret } // end of method Program::Main
nameof(args)方式的IL程式碼:
.method private hidebysig static void Main(string[] args) cil managed { .entrypoint // Code size 22 (0x16) .maxstack 2 .locals init ([0] bool V_0) IL_0000: nop IL_0001: ldarg.0 IL_0002: ldnull IL_0003: ceq IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: brfalse.s IL_0015 IL_0009: nop IL_000a: ldstr "args" IL_000f: newobj instance void [mscorlib]System.ArgumentNullException::.ctor(string) IL_0014: throw IL_0015: ret } // end of method Program::Main
一樣一樣的,我是沒看出來有任何的差異,so,這個運算子也是一個編譯器層面提供的語法糖,編譯後就沒有nameof的影子了。
三、 nameof 注意事項
nameof可以用於獲取具名錶達式的當前名字的簡單字串表示:
using System; namespace ConsoleApp1 { class Program { static void Main(string[] args) { string strL= "hello"; Console.WriteLine(nameof(strL));//CC Console.WriteLine(nameof(System.ConsoleColor));//ConsoleColor Console.ReadKey(); } } }
第一個語句輸出"strL",因為它是當前的名字,那麼nameof運算子的結果就是"strL"。
第二個語句輸出了"ConsoleColor",因為它是System.ConsoleColor的簡單字串表示,而非取得它的完全限定名,如果想取得"System.ConsoleColor",那麼請使用
typeof(System.ConsoleColor).FullName