.NET 幫助

C# Nameof(它如何為開發者工作)

發佈 2024年3月6日
分享:

在 C# 6.0 中引入的 'nameof' 運算子,是一個編譯時期構造,旨在解決通過名稱引用程序元素以及默默打破運行時行為的挑戰。其主要目的是消除硬編碼字符串的需求,提供一種更易維護且錯誤抵抗性的方式。在本文中,我們將探討 C# 中的 nameof 運算子並介紹 IronPDF NuGet 用程式生成 PDF 文件的庫。

'nameof' 運算符的基本語法

'nameof' 運算符的基本語法是簡單的。它將一個元素作為參數,並以字符串形式返回其名稱。請參考以下示例:

static void Main()
{
 //string name
  string myVariable = nameof(myVariable);
}
static void Main()
{
 //string name
  string myVariable = nameof(myVariable);
}
Shared Sub Main()
 'string name
  Dim myVariable As String = NameOf(myVariable)
End Sub
VB   C#

在這種情況下,‘nameof(我的變數)' 產生字串輸入 "myVariable"。該運算子可以應用於各種程式碼元素,包括變數、類型、成員等。

'nameof' 運算子的好處

程式碼可維護性

'nameof' 運算子的其中一個顯著優勢是對程式碼可維護性的正面影響。取代將名稱硬編碼為字串,開發者可以使用 'nameof',確保在名稱變更時引用能自動更新。

static void Main()
{
// Without using nameof
Logger.Log("Error: The variable 'myVariable' is null.");
// Using nameof for improved maintainability
Logger.Log($"Error: The variable '{nameof(myVariable)}' is null.");
}
static void Main()
{
// Without using nameof
Logger.Log("Error: The variable 'myVariable' is null.");
// Using nameof for improved maintainability
Logger.Log($"Error: The variable '{nameof(myVariable)}' is null.");
}
Shared Sub Main()
' Without using nameof
Logger.Log("Error: The variable 'myVariable' is null.")
' Using nameof for improved maintainability
Logger.Log($"Error: The variable '{NameOf(myVariable)}' is null.")
End Sub
VB   C#

編譯時安全性

'nameof' 通過消除名稱中的拼寫錯誤或不一致性,增強了編譯時的安全性。任何變數名稱的拼寫錯誤或修改都會觸發編譯時錯誤,從而減少了運行時問題的可能性。

static void Main()
{
// Compile-time error if 'myVariable' is misspelled
string myVariable = nameof(myVariabell);
}
static void Main()
{
// Compile-time error if 'myVariable' is misspelled
string myVariable = nameof(myVariabell);
}
Shared Sub Main()
' Compile-time error if 'myVariable' is misspelled
Dim myVariable As String = NameOf(myVariabell)
End Sub
VB   C#

重構支援

'nameof' 運算子無縫整合重構工具,提供重新命名變數、類型或成員時的輕鬆體驗。所有 'nameof' 參考都會自動更新。

static void Main()
{
// Before renaming local variable 'myVariable' to 'newVariable'
string myVariable = nameof(myVariable);
// After renaming local variable  'myVariable' to 'newVariable'
string newVariable = nameof(newVariable);
}
static void Main()
{
// Before renaming local variable 'myVariable' to 'newVariable'
string myVariable = nameof(myVariable);
// After renaming local variable  'myVariable' to 'newVariable'
string newVariable = nameof(newVariable);
}
Shared Sub Main()
' Before renaming local variable 'myVariable' to 'newVariable'
Dim myVariable As String = NameOf(myVariable)
' After renaming local variable  'myVariable' to 'newVariable'
Dim newVariable As String = NameOf(newVariable)
End Sub
VB   C#

增強除錯功能

在除錯期間,nameof使程式碼更加資訊化和可讀。日誌記錄語句、異常消息和其他除錯輸出變得簡潔且具上下文相關性。

static void Main()
{
// Without using nameof throw new ArgumentNullException("myVariable", "The variable cannot be null."); 
// Using nameof for improved debugging 
throw new ArgumentNullException(nameof(myVariable), "The variable cannot be null.");
}
static void Main()
{
// Without using nameof throw new ArgumentNullException("myVariable", "The variable cannot be null."); 
// Using nameof for improved debugging 
throw new ArgumentNullException(nameof(myVariable), "The variable cannot be null.");
}
Shared Sub Main()
' Without using nameof throw new ArgumentNullException("myVariable", "The variable cannot be null."); 
' Using nameof for improved debugging 
Throw New ArgumentNullException(NameOf(myVariable), "The variable cannot be null.")
End Sub
VB   C#

此處的 throw new ArgumentNullException(nameof) 如果變數未宣告則會拋出異常。

'nameof' 操作符的實際使用案例

反射

在使用反射時,nameof 運算符使得獲取類型、屬性或方法的名稱變得更簡單,無需使用硬編碼字符串。

Type type = typeof(MyClass);
string typeName = nameof(MyClass);
Type type = typeof(MyClass);
string typeName = nameof(MyClass);
Dim type As Type = GetType([MyClass])
Dim typeName As String = NameOf([MyClass])
VB   C#

範例類別 MyClass 可以是一個硬編碼的字串,但我們可以使用反射來動態獲取類別名稱。變量名稱 type 包含類別名稱,然後使用 nameof 關鍵字來獲取類別實例的名稱。它們不是相同的名稱。

日誌記錄和例外處理

'nameof' 在日誌陳述和例外訊息中顯得無比珍貴,使它們更易讀且更少出錯。

Logger.Log($"Error: The property '{nameof(MyClass.MyProperty)}' is out of range.");
Logger.Log($"Error: The property '{nameof(MyClass.MyProperty)}' is out of range.");
Logger.Log($"Error: The property '{NameOf([MyClass].MyProperty)}' is out of range.")
VB   C#

範例

在這個範例中,我們會建立一個簡單的類別來表示一個人,並且我們會使用 nameof 運算符來改進日誌和錯誤訊息的記錄。

using System;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }    
    //method name
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing."); // display string
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public string DoSomething()
{
}
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string
        person.LastName = "Doe"; // string
        // Display the full name string again
        person.DisplayFullName();
    }
}
using System;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }    
    //method name
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing."); // display string
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public string DoSomething()
{
}
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    static void Main()
    {
        // Create an instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string
        person.LastName = "Doe"; // string
        // Display the full name string again
        person.DisplayFullName();
    }
}
Imports System
Friend Class Person
	Public Property FirstName() As String
	Public Property LastName() As String
	'method name
	Public Sub DisplayFullName()
		If String.IsNullOrEmpty(FirstName) String.IsNullOrEmpty(LastName) Then
			LogError($"Invalid name: {NameOf(FirstName)} or {NameOf(LastName)} is missing.") ' display string
		Else
			Console.WriteLine($"Full Name: {FirstName} {LastName}")
		End If
	End Sub
	Public Function DoSomething() As String
	End Function
	Private Sub LogError(ByVal errorMessage As String)
		Console.ForegroundColor = ConsoleColor.Red
		Console.WriteLine($"Error: {errorMessage}")
		Console.ResetColor()
	End Sub
End Class
Friend Class Program
	Shared Sub Main()
		' Create an instance of the Person class
		Dim person As New Person()
		' Attempt to display the full name
		person.DisplayFullName()
		' Set the properties
		person.FirstName = "John" ' string
		person.LastName = "Doe" ' string
		' Display the full name string again
		person.DisplayFullName()
	End Sub
End Class
VB   C#

解釋

  1. 我們有一個 Person 類別,具有 FirstName 和 LastName 屬性,還有一個名為 DisplayFullName 的方法,在顯示完整姓名之前檢查這兩個屬性是否已設置。

  2. 在名為 DisplayFullName 的方法內,我們使用 nameof(名字) 和 nameof(姓氏) 參考屬性名稱作為字串文字。這樣可以提高代碼的可讀性,並確保如果屬性名稱發生變更,屬性定義和相應的錯誤訊息會在編譯過程中自動更新。

  3. 方法名稱 LogError 利用了 nameof 動態地將屬性名稱包含在錯誤訊息中。

  4. 在 Main 方法中,我們創建了一個 Person 類的實例,嘗試在未設置屬性時顯示全名,然後設置屬性定義並再次顯示全名。

public string DoSomething 可以使用 nameof 運算子執行一些業務邏輯。

當您運行此程序時,您會看到編譯器錯誤訊息動態地包含了屬性名稱,提供更多的上下文信息,從而使識別缺少哪個屬性變得更容易:

C# Nameof(開發者的工作原理):圖1 - 屬性變更事件

這個範例展示了nameof運算符如何通過在屬性名稱更改時自動更新引用來提高代碼可維護性,並在開發過程中通過更具信息性的細節來增強錯誤消息。

介紹 IronPDF

IronPDF 是一個來自 的 C# PDF 庫 Iron Software 可以用作 PDF 生成器和閱讀器。這裡我們介紹基本功能。欲了解更多信息,請參閱文檔。

IronPDF 的顯著功能是其 HTML轉PDF 功能,保留您的佈局和樣式。它從網頁內容生成 PDF,使其非常適合報告、發票和文件。HTML 檔案、URL 和 HTML 字串都可以無縫轉換為 PDF。

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

安裝

IronPDF 可以使用 NuGet 封裝管理員主控台或 Visual Studio 封裝管理員安裝。

dotnet add package IronPdf
dotnet add package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronPdf
VB   C#

C# Nameof(對於開發人員的工作方式):圖 2 - 使用 NuGet 套件管理器搜索「ironpdf」安裝 IronPDF。

namespace OrderBy;
using System;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing.");
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public void PrintPdf()
    {
        Console.WriteLine("Generating PDF using IronPDF.");
        string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {FirstName}!</h1>
<p>First Name: {FirstName}</p>
<p>First Name: {LastName}</p>
</body>
</html>";
// Create a new PDF document
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("person.pdf"); 
    }
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    static void Main()
    {
        // Create an  instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string literal
        person.LastName = "Doe"; // string literal
        // Display the full name again
        person.DisplayFullName();
    }
}
namespace OrderBy;
using System;
class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public void DisplayFullName()
    {
        if (string.IsNullOrEmpty(FirstName) 
 string.IsNullOrEmpty(LastName))
        {
            LogError($"Invalid name: {nameof(FirstName)} or {nameof(LastName)} is missing.");
        }
        else
        {
            Console.WriteLine($"Full Name: {FirstName} {LastName}");
        }
    }
    public void PrintPdf()
    {
        Console.WriteLine("Generating PDF using IronPDF.");
        string content = $@"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {FirstName}!</h1>
<p>First Name: {FirstName}</p>
<p>First Name: {LastName}</p>
</body>
</html>";
// Create a new PDF document
        var pdfDocument = new ChromePdfRenderer();
        pdfDocument.RenderHtmlAsPdf(content).SaveAs("person.pdf"); 
    }
    private void LogError(string errorMessage)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine($"Error: {errorMessage}");
        Console.ResetColor();
    }
}
class Program
{
    static void Main()
    {
        // Create an  instance of the Person class
        Person person = new Person();
        // Attempt to display the full name
        person.DisplayFullName();
        // Set the properties
        person.FirstName = "John"; // string literal
        person.LastName = "Doe"; // string literal
        // Display the full name again
        person.DisplayFullName();
    }
}
Imports System

Namespace OrderBy
	Friend Class Person
		Public Property FirstName() As String
		Public Property LastName() As String
		Public Sub DisplayFullName()
			If String.IsNullOrEmpty(FirstName) String.IsNullOrEmpty(LastName) Then
				LogError($"Invalid name: {NameOf(FirstName)} or {NameOf(LastName)} is missing.")
			Else
				Console.WriteLine($"Full Name: {FirstName} {LastName}")
			End If
		End Sub
		Public Sub PrintPdf()
			Console.WriteLine("Generating PDF using IronPDF.")
			Dim content As String = $"<!DOCTYPE html>
<html>
<body>
<h1>Hello, {FirstName}!</h1>
<p>First Name: {FirstName}</p>
<p>First Name: {LastName}</p>
</body>
</html>"
	ignore ignore ignore ignore ignore ignore ignore var pdfDocument = New ChromePdfRenderer()
			pdfDocument.RenderHtmlAsPdf(content).SaveAs("person.pdf")
		End Sub
		Private Sub LogError(ByVal errorMessage As String)
			Console.ForegroundColor = ConsoleColor.Red
			Console.WriteLine($"Error: {errorMessage}")
			Console.ResetColor()
		End Sub
	End Class
	Friend Class Program
		Shared Sub Main()
			' Create an  instance of the Person class
			Dim person As New Person()
			' Attempt to display the full name
			person.DisplayFullName()
			' Set the properties
			person.FirstName = "John" ' string literal
			person.LastName = "Doe" ' string literal
			' Display the full name again
			person.DisplayFullName()
		End Sub
	End Class
End Namespace
VB   C#

在這裡,IronPDF 用於使用本地變量內容和 pdfDocument 生成 PDF,可以在 PrintPdf 方法中看到。

輸出

C# Nameof(對開發人員的操作方式):圖 3 - 程式輸出

PDF 生成

C# Nameof(對開發者的運作方式):圖4 - PDF輸出

授權 (免費試用)

IronPDF這個密鑰需要放置在 appsettings.json。

"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'"IronPdf.LicenseKey": "your license key"
VB   C#

提供您的電子郵件以獲取試用許可證。

結論

C# 的 'nameof' 運算子已經成為開發者尋求更清晰、更安全和更易維護代碼的一個常規工具。它提高代碼可讀性的能力,再加上編譯時的安全性和無縫的重構支持,使之成為 C# 開發者工具包中不可或缺的一部分。隨著開發社區繼續接受和利用 'nameof' 運算子,它將在塑造 C# 編程的未來中起到關鍵作用。IronPDF 是一個方便的 NuGet 包,可以快速輕鬆地生成 PDF。

< 上一頁
C# 運算符(如何對開發者起作用)
下一個 >
HashSet C#(開發人員如何使用)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >