跳過到頁腳內容
.NET幫助

C# Nameof(對於開發者的運行原理)

在 C# 6.0 中引入的"nameof"運算元是一種編譯時構造,旨在解決以其名稱指代程式元素並默默破壞執行時行為的難題。 其主要目的是消除對硬編碼字串的需求,提供更易維護且不易出錯的方法。 在本文中,我們將探討 C# 中的 nameof 運算符,同時介紹 IronPDF Library on NuGet 函式庫,以程式化的方式產生 PDF 文件。

'nameof'操作符的基本語法

nameof "運算符號的基本語法很簡單。 它以元素為參數,並以字串形式回傳其名稱。 請考慮以下範例:

static void Main()
{
    // Declare a string variable
    string myVariable = nameof(myVariable);
    Console.WriteLine(myVariable); // Output: "myVariable"
}
static void Main()
{
    // Declare a string variable
    string myVariable = nameof(myVariable);
    Console.WriteLine(myVariable); // Output: "myVariable"
}
Shared Sub Main()
	' Declare a string variable
	Dim myVariable As String = NameOf(myVariable)
	Console.WriteLine(myVariable) ' Output: "myVariable"
End Sub
$vbLabelText   $csharpLabel

在本例中,"nameof(myVariable) "產生字串 "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
$vbLabelText   $csharpLabel

編譯時安全性

nameof'可消除名稱中的錯字或不一致的風險,從而增強編譯時的安全性。 變量名稱的任何拼寫錯誤或修改都會觸發編譯時錯誤,減少發生執行時問題的機會。

static void Main()
{
    // Compile-time error if 'myVariable' is misspelled
    string myVariable;
    string variableName = nameof(myVariable);

    Console.WriteLine(variableName);
}
static void Main()
{
    // Compile-time error if 'myVariable' is misspelled
    string myVariable;
    string variableName = nameof(myVariable);

    Console.WriteLine(variableName);
}
Shared Sub Main()
	' Compile-time error if 'myVariable' is misspelled
	Dim myVariable As String
	Dim variableName As String = NameOf(myVariable)

	Console.WriteLine(variableName)
End Sub
$vbLabelText   $csharpLabel

重構支援。

nameof'運算符號可與重構工具無縫整合,在重新命名變數、類型或成員時提供省事的體驗。 所有 "nameof "引用都會自動更新。

static void Main()
{
    // Before renaming local variable 'myVariable' to 'newVariable'
    string myVariableNameChange = nameof(myVariableNameChange);
    // After renaming local variable 'myVariable' to 'newVariable'
    string newVariableNameChange = nameof(newVariableNameChange);

    Console.WriteLine(newVariableNameChange);
}
static void Main()
{
    // Before renaming local variable 'myVariable' to 'newVariable'
    string myVariableNameChange = nameof(myVariableNameChange);
    // After renaming local variable 'myVariable' to 'newVariable'
    string newVariableNameChange = nameof(newVariableNameChange);

    Console.WriteLine(newVariableNameChange);
}
Shared Sub Main()
	' Before renaming local variable 'myVariable' to 'newVariable'
	Dim myVariableNameChange As String = NameOf(myVariableNameChange)
	' After renaming local variable 'myVariable' to 'newVariable'
	Dim newVariableNameChange As String = NameOf(newVariableNameChange)

	Console.WriteLine(newVariableNameChange)
End Sub
$vbLabelText   $csharpLabel

增強調試

在除錯時,"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
$vbLabelText   $csharpLabel

這裡的 throw new ArgumentNullException 會在變數未被宣告時產生異常。

'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])
$vbLabelText   $csharpLabel

範例類別 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.")
$vbLabelText   $csharpLabel

範例

在本範例中,我們將建立一個代表 Person 的簡單類別,並使用 nameof 運算子來改善日誌和錯誤訊息。

using System;

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    // Method that displays the full name of the person
    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}");
        }
    }

    // Custom error logging method that highlights errors
    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 without setting the properties
        person.DisplayFullName();

        // Set the properties and display the full name again
        person.FirstName = "John";
        person.LastName = "Doe";
        person.DisplayFullName();
    }
}
using System;

class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    // Method that displays the full name of the person
    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}");
        }
    }

    // Custom error logging method that highlights errors
    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 without setting the properties
        person.DisplayFullName();

        // Set the properties and display the full name again
        person.FirstName = "John";
        person.LastName = "Doe";
        person.DisplayFullName();
    }
}
Imports System

Friend Class Person
	Public Property FirstName() As String
	Public Property LastName() As String

	' Method that displays the full name of the person
	Public Sub DisplayFullName()
		If String.IsNullOrEmpty(FirstName) OrElse 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

	' Custom error logging method that highlights errors
	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 without setting the properties
		person.DisplayFullName()

		' Set the properties and display the full name again
		person.FirstName = "John"
		person.LastName = "Doe"
		person.DisplayFullName()
	End Sub
End Class
$vbLabelText   $csharpLabel

說明

1.我們有一個 Person 類,具有 FirstNameLastName 屬性,以及一個方法 DisplayFullName 在顯示全名之前,會檢查這兩個屬性是否都已設定。 2.在方法 DisplayFullName 中,我們使用 nameof(FirstName)nameof(LastName) 來以字串字面形式引用屬性名稱。 這可提高程式碼的可讀性,並確保如果屬性名稱改變,屬性定義和對應的錯誤訊息都會在編譯過程中自動更新。 3.方法 LogError 利用 nameof 在錯誤訊息中動態包含屬性名稱。 4.在 Main 方法中,我們建立一個 Person 類的實體,嘗試在未設定屬性的情況下顯示全名,然後再設定屬性並再次顯示全名。

當您執行此程式時,您會發現錯誤訊息動態地加入了屬性名稱,提供了更多的上下文,讓您更容易識別出缺少了哪個屬性。

本範例展示 nameof 運算符如何在屬性名稱變更時自動更新引用,以改善程式碼的可維護性,並在開發過程中以更翔實的詳細資訊增強錯誤訊息。

介紹 IronPDF。

IronPDF for C#.NETIron Software 的 PDF 函式庫,可用作 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
$vbLabelText   $csharpLabel

安裝

IronPDF 可使用 NuGet 套件管理員控制台或 Visual Studio 套件管理員進行安裝。

dotnet add package IronPdf
dotnet add package IronPdf
SHELL

!C# Nameof (How It Works For Developers):圖 2 - 使用 NuGet Package Manager 安裝 IronPDF,方法是在 NuGet Package Manager 的搜尋列中搜尋 "ironpdf"。

namespace OrderBy;

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>Last 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";
        person.LastName = "Doe";

        // Display the full name again
        person.DisplayFullName();

        // Generate a PDF
        person.PrintPdf();
    }
}
namespace OrderBy;

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>Last 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";
        person.LastName = "Doe";

        // Display the full name again
        person.DisplayFullName();

        // Generate a PDF
        person.PrintPdf();
    }
}
Namespace OrderBy

	Friend Class Person
		Public Property FirstName() As String
		Public Property LastName() As String

		Public Sub DisplayFullName()
			If String.IsNullOrEmpty(FirstName) OrElse 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>Last 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"
			person.LastName = "Doe"

			' Display the full name again
			person.DisplayFullName()

			' Generate a PDF
			person.PrintPdf()
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

這裡 IronPDF 使用本機變數 contentpdfDocument 產生 PDF,可以在 PrintPdf 方法中看到。

Output

C# Nameof (How It Works For Developers):圖 3 - 程式輸出

PDF生成

C# Nameof (How It Works For Developers):圖 4 - PDF 輸出

授權(可免費試用)

有關授權,請查看 試用授權資訊。 此 key 需要放在 appsettings.json 中。

"IronPdf.LicenseKey": "your license key"

提供您的電子郵件以取得試用授權。

結論

C# 的"nameof"運算元已經成為開發人員尋求更簡潔、安全和可維護程式碼的主要工具。 它能夠增強程式碼的可讀性,加上編譯時的安全性和無縫重組支援,使其成為 C# 開發人員工具包中不可或缺的工具。 隨著開發社群持續接受並運用"nameof"運算元,它將在 C# 程式設計的未來扮演舉足輕重的角色。 IronPDF 是一個方便的 NuGet 套件,可用來快速輕鬆地產生 PDF。

常見問題解答

在 C# 中,"nameof "運算符號有何作用?

C# 中的「nameof」操作符會以字串形式回傳程式元素的名稱,例如變數、類型或成員。它消除了硬編碼字串,提高了程式碼的可讀性和可維護性。

nameof "運算符號如何改善程式碼重整?

nameof "運算符號可在元素重命名時自動更新引用,減少錯誤並提昇重構流程的效率,有助於程式碼重構。

nameof "運算符號在調試中有什麼好處?

nameof "運算符能動態地提供程式元素的實際名稱,使記錄語句和異常訊息更具描述性且不易出錯,從而增強了除錯功能。

C# 中 'nameof' 運算符的實際用途是什麼?

nameof "操作符的實際用途包括在日誌和異常處理中使用,透過包含變數或方法的實際名稱,使訊息內容更豐富。

如何用 C# 將 HTML 內容轉換成 PDF?

您可以使用 IronPDF 以 C# 將 HTML 內容轉換為 PDF。IronPDF 提供將 HTML 字串、檔案和 URL 轉換為格式良好的 PDF 文件的方法,非常適合報告和文件。

IronPDF 函式庫的安裝步驟是什麼?

要安裝 IronPDF,請使用 Visual Studio 中的 NuGet 套件管理程式,在套件管理程式主控台中執行指令 dotnet add package IronPdf

IronPDF 可以處理複雜佈局的 HTML 到 PDF 的轉換嗎?

是的,IronPdf 旨在處理 HTML 到 PDF 的轉換,同時保留複雜的版面設計和樣式,確保輸出的 PDF 與原始 HTML 設計非常吻合。

使用 IronPDF 生成 PDF 有哪些優點?

IronPDF 可從 HTML 內容無縫生成 PDF,支援各種內容類型,並為開發人員提供易於使用的 API,使其成為以程式化方式製作專業文件的多功能工具。

Jacob Mellor, Team Iron 首席技术官
首席技术官

Jacob Mellor 是 Iron Software 的首席技術官,作為 C# PDF 技術的先鋒工程師。作為 Iron Software 核心代碼的原作者,他自開始以來塑造了公司產品架構,與 CEO Cameron Rimington 一起將其轉變為一家擁有超過 50 名員工的公司,為 NASA、特斯拉 和 全世界政府機構服務。

Jacob 持有曼徹斯特大學土木工程一級榮譽学士工程學位(BEng) (1998-2001)。他於 1999 年在倫敦開設了他的第一家軟件公司,並於 2005 年製作了他的首個 .NET 組件,專注於解決 Microsoft 生態系統內的複雜問題。

他的旗艦產品 IronPDF & Iron Suite .NET 庫在全球 NuGet 被安裝超過 3000 萬次,其基礎代碼繼續為世界各地的開發工具提供動力。擁有 25 年的商業經驗和 41 年的編碼專業知識,Jacob 仍專注於推動企業級 C#、Java 及 Python PDF 技術的創新,同時指導新一代技術領袖。