在生產環境中測試,無水印。
在任何需要的地方都能運行。
獲得 30 天的全功能產品。
在幾分鐘內上手運行。
試用產品期間完全訪問我們的支援工程團隊
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);
}
在這種情況下,‘nameof(我的變數)產生字串輸入 "myVariable"。 運算符可以應用於各種程式碼元素,包括變數、類型、成員等。
'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.");
}
「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);
}
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);
}
在除錯過程中,'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.");
}
此處的 throw new ArgumentNullException(nameof) 如果變數未宣告則會拋出異常。
'nameof' 操作符的實際使用案例
在使用反射時,nameof
運算子簡化了獲取類型、屬性或方法名稱的過程,無需使用硬編碼的字符串。
Type type = typeof(MyClass);
string typeName = nameof(MyClass);
Type type = typeof(MyClass);
string typeName = nameof(MyClass);
範例類別 MyClass 可以是一個硬編碼的字串,但我們可以使用反映來動態獲取類別名稱。 變數名稱類型具有類別名稱,然後使用 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.");
在此示例中,我們將創建一個表示 Person 的簡單類,並使用 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();
}
}
我們有一個具有 FirstName 和 LastName 屬性的 Person 類別,並有一個名為 DisplayFullName 的方法,在顯示全名之前會檢查這兩個屬性是否已設置。
在方法名稱 DisplayFullName 內,我們使用 nameof(名字)和 nameof(姓氏)將屬性名稱作為字串字面值引用。 這提高了代碼的可讀性,並確保如果屬性名稱發生變更,則屬性定義和相應的錯誤信息在編譯過程中會自動更新。
方法名稱 LogError 利用 nameof 可以在錯誤訊息中動態包含屬性名稱。
在 Main 方法中,我們創建了一個 Person 類的實例,嘗試在未設定屬性的情況下顯示全名,然後設置屬性定義並再次顯示全名。
公共字串 DoSomething 可以使用 nameof 運算子執行一些業務邏輯。
當您運行此程式時,您將看到編譯器錯誤訊息會動態結合屬性名稱,提供更多的上下文,使其更容易識別哪個屬性缺失:
此示例説明瞭如何通過在屬性名稱更改時自動更新引用的 nameof 運算符來提高程式碼的可維護性,並在開發過程中通過更具資訊性的詳細資訊來增強錯誤消息。
IronPDF for C#.NET是 Iron 的 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");
}
}
可以使用 NuGet 套件管理控制台或 Visual Studio 套件管理器安裝 IronPDF。
dotnet add package IronPdf
dotnet add package 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();
}
}
在這裡,IronPDF 被用來生成一個 PDF,使用本地變量 content 和 pdfDocument,這可以在 PrintPdf 方法中看到。
輸出
PDF 生成
若需授權,請參閱試用許可證資訊. 此鍵需要放置在 appsettings.json 中。
"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"
提供您的電子郵件以獲取試用許可證。
C# 的 'nameof' 運算子已成為開發者尋求更乾淨、更安全以及更具可維護性代碼的常用工具。 其提升程式碼可讀性、提供編譯時安全性以及無縫重構支持的能力,使其成為 C# 開發者工具箱中不可或缺的工具。 隨著開發社區不斷接受並利用 'nameof' 運算子,它將在塑造 C# 程式設計的未來方面發揮關鍵作用。 IronPDF 是一個方便的 NuGet 套件,可以快速輕鬆地生成 PDF。