在實際環境中測試
在生產環境中測試無浮水印。
在任何需要的地方都能運作。
在 C# 6.0 中引入的 'nameof' 運算子,是一個編譯時期構造,旨在解決通過名稱引用程序元素以及默默打破運行時行為的挑戰。其主要目的是消除硬編碼字符串的需求,提供一種更易維護且錯誤抵抗性的方式。在本文中,我們將探討 C# 中的 nameof 運算子並介紹 IronPDF NuGet 用程式生成 PDF 文件的庫。
'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
在這種情況下,‘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.");
}
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
'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
'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
在除錯期間,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
此處的 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])
範例類別 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.")
在這個範例中,我們會建立一個簡單的類別來表示一個人,並且我們會使用 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
我們有一個 Person 類別,具有 FirstName 和 LastName 屬性,還有一個名為 DisplayFullName 的方法,在顯示完整姓名之前檢查這兩個屬性是否已設置。
在名為 DisplayFullName 的方法內,我們使用 nameof(名字) 和 nameof(姓氏) 參考屬性名稱作為字串文字。這樣可以提高代碼的可讀性,並確保如果屬性名稱發生變更,屬性定義和相應的錯誤訊息會在編譯過程中自動更新。
方法名稱 LogError 利用了 nameof 動態地將屬性名稱包含在錯誤訊息中。
public string DoSomething 可以使用 nameof 運算子執行一些業務邏輯。
當您運行此程序時,您會看到編譯器錯誤訊息動態地包含了屬性名稱,提供更多的上下文信息,從而使識別缺少哪個屬性變得更容易:
這個範例展示了nameof運算符如何通過在屬性名稱更改時自動更新引用來提高代碼可維護性,並在開發過程中通過更具信息性的細節來增強錯誤消息。
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
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
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
在這裡,IronPDF 用於使用本地變量內容和 pdfDocument 生成 PDF,可以在 PrintPdf 方法中看到。
輸出
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"
提供您的電子郵件以獲取試用許可證。
C# 的 'nameof' 運算子已經成為開發者尋求更清晰、更安全和更易維護代碼的一個常規工具。它提高代碼可讀性的能力,再加上編譯時的安全性和無縫的重構支持,使之成為 C# 開發者工具包中不可或缺的一部分。隨著開發社區繼續接受和利用 'nameof' 運算子,它將在塑造 C# 編程的未來中起到關鍵作用。IronPDF 是一個方便的 NuGet 包,可以快速輕鬆地生成 PDF。