(C# 參考) 的 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
如上述範例所示,在類型和命名空間的情況下,產生的名稱不是 完整名稱。
在 逐字識別碼的情況下, @
字元不是名稱的一部分,如下列範例所示:
var @new = 5;
Console.WriteLine(nameof(@new)); // output: new
運算式 nameof
會在編譯時期進行評估,而且在執行時間沒有任何作用。
您可以使用 nameof
運算式讓引數檢查程式碼更容易維護:
public string Name
{
get => name;
set => name = value ?? throw new ArgumentNullException(nameof(value), $"{nameof(Name)} cannot be null");
}
運算子的 nameof
引數必須位於範圍內。 從 C# 11 開始,參數和類型參數會位於 屬性內,以供 運算子使用 nameof
。 下列範例顯示 nameof
用於方法、區域函式和 Lambda 運算式的參數:
[ParameterString(nameof(msg))]
public static void Method( string msg)
{
[ParameterString(nameof(param))]
void LocalFunction(string param) { }
var lambdaExpression = [ParameterString(nameof(aNumber))] (int aNumber) => aNumber.ToString();
}
使用可為 Null 的分析屬性時,在 nameof
參數上使用 最有用。
C# 語言規格
如需詳細資訊,請參閱 C# 語言規格的 Nameof 運算式一節。