跳至页脚内容
.NET 帮助

C# Nameof(开发人员如何使用)

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

示例

在此示例中,我们将创建一个简单的类来代表一个人,并使用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#.NET is a PDF library from Iron Software的PDF库,可以用作PDF生成器和阅读器。 这里我们介绍基本功能。 有关更多信息,请参阅文档。

IronPDF的突出特色是HTML转PDF转换功能,保持您的布局和样式。 它从网页内容生成 PDF,非常适合用于报告、发票和文档。 下面是一个简化示例,演示了如何在 CQRS 设置中使用 IronPDF 来生成 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

安装

可以使用NuGet包管理器控制台或Visual Studio包管理器安装IronPDF。

dotnet add package IronPdf
dotnet add package IronPdf
SHELL

C# Nameof(它对开发者的作用):图2 - 使用NuGet包管理器安装IronPDF,在NuGet包管理器的搜索栏中搜索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方法中看到。

输出

C# Nameof(它对开发者的作用):图3 - 程序输出

PDF生成

C# Nameof(它对开发者的作用):图4 - PDF输出

许可(提供免费试用)

有关许可证,请查看试用许可证信息。 此密钥需要放置在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,使其成为以编程方式创建专业文档的多功能工具。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。