.NET幫助 C# Nameof(對於開發者的運行原理) Curtis Chau 更新日期:7月 28, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article C# 6.0 引入的 'nameof' 運算符是一種在編譯時期構建的工具,用來解決通過名稱引用程式元素及其在運行時悄然損壞的行為。 它的主要目的是消除硬編碼字符串的需求,提供一種更易於維護且抗錯誤的方法。 在本文中,我們將探索 C# 的 nameof 運算符,並介紹如何使用NuGet 上的 IronPDF Library 程式設計生成 PDF 文件。 'nameof' 運算符的基本語法 'nameof' 運算符的基本語法很簡單。 它接受一個元素作為參數,並以字符串形式返回其名稱。 在此示例中,IronPDF用於將HTML內容呈現為PDF文檔,然後保存到指定位置。 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 解釋 我們有一個 Person 類,具有 FirstName 和 LastName 屬性,以及一個方法 DisplayFullName,在顯示全名之前檢查兩個屬性是否已設置。 在方法 DisplayFullName 中,我們使用 nameof(FirstName) 和 nameof(LastName) 以字符串文字形式引用屬性名稱。 這改善了程式碼可讀性,並確保如果屬性名稱發生更改,則屬性定義和相應的錯誤消息會在編譯期間自動更新。 方法 LogError 利用 nameof 以動態地將屬性名稱包含在錯誤消息中。 在 Main 方法中,我們創建了 Person 類的實例,嘗試不設置屬性就顯示全名,然後設置屬性並再次顯示全名。 運行此程式時,您會看到錯誤消息動態地包含了屬性名稱,提供了更多上下文,並使更容易識別哪個屬性缺失。 此示例演示了如何使用 nameof 運算符在屬性名稱更改時自動更新引用,並在開發期間用更具信息性的細節增強錯誤消息,從而提高程式碼的可維護性。 介绍 IronPDF IronPDF for C#.NET is a PDF library from Iron 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 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 用於生成 PDF,使用本地變數 content 和 pdfDocument,可以在 PrintPdf 方法中看到。 輸出 PDF 生成 許可(可用免費試用) 有關許可資訊,請查看 試用許可證資訊。 該密鑰需要放置在 appsettings.json 中。 "IronPdf.LicenseKey": "your license key" 提供您的電子郵件以獲取試用許可證。 結論 C# 的 'nameof' 運算符已成為尋求更清晰、更安全、更易於維護的程式碼的開發人員的基本工具。 它對程式碼可讀性的增強能力,加上編譯時安全性和無縫重構支持,使其成為 C# 開發人員工具集中的不可或缺工具。 隨著開發社群繼續接受並利用 'nameof' 運算符,它將在塑造 C# 編程的未來中發揮關鍵作用。 IronPDF 是一個便捷的 NuGet 套件,可以快速輕鬆地生成 PDF。 常見問題解答 C# 中的 'nameof' 運算符的作用是什麼? C# 中的 'nameof' 運算符以字串形式返回程式元素的名稱,例如變數、類型或成員。它通過消除硬編碼字串來提高程式碼的可讀性和可維護性。 C# 中的 'nameof' 運算符如何改進程式碼重構? 'nameof' 運算符在元素重命名時自動更新引用,有助于程式碼重構,减少錯誤並提高重構過程的效率。 C# 中 '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 供開發人員使用,使其成為創建專業文檔的多功能工具。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 C# 運算符(對於開發者的運行原理)HashSet C#(對於開發者的運...