.NET 帮助

C# Nameof(它如何为开发人员工作)

发布 2024年三月6日
分享:

nameof "操作符在 C# 6.0 中引入,它是一种编译时结构,旨在解决通过名称引用程序元素和无声地破坏运行时行为的难题。它的主要目的是消除对硬编码字符串的需求,提供一种更易于维护和抗错的方法。在本文中,我们将探讨 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);
}
Shared Sub Main()
 'string name
  Dim myVariable As String = NameOf(myVariable)
End Sub
VB   C#

在这种情况下,"姓名(我的变量)产生字符串输入 "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
VB   C#

编译时安全

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
VB   C#

重构支持

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
VB   C#

增强调试

在调试过程中,"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
VB   C#

在这里,如果变量未声明,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])
VB   C#

示例类 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.");
Logger.Log($"Error: The property '{NameOf([MyClass].MyProperty)}' is out of range.")
VB   C#

示例

在这个示例中,我们将创建一个代表 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();
    }
}
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
VB   C#

解释

1.我们有一个带有 FirstName 和 LastName 属性的 Person 类,以及一个名为 DisplayFullName 的方法,该方法用于在显示全名前检查这两个属性是否都已设置。

2.在方法 DisplayFullName 中,我们使用 nameof(名) 和名称(姓氏) 以字符串字面形式引用属性名。这样可以提高代码的可读性,并确保在属性名称发生变化时,属性定义和相应的错误信息都会在编译过程中自动更新。

3.方法 LogError 利用 nameof 将属性名动态包含在错误信息中。

4.在 Main 方法中,我们创建了 Person 类的实例,尝试在不设置属性的情况下显示全名,然后设置属性定义并再次显示全名。

公共字符串 DoSomething 可以使用 nameof 操作符执行一些业务逻辑。

当你运行这个程序时,你会发现编译器错误信息动态地包含了属性名称,提供了更多的上下文,使你更容易确定缺少了哪个属性:

C# Nameof(如何为开发人员工作):图 1 - 属性更改事件

本例演示了 nameof 操作符如何在属性名称发生变化时自动更新引用,从而提高代码的可维护性,并在开发过程中通过提供更多信息细节来增强错误信息。

IronPDF 简介

IronPDF 是一个来自 铁软件 可用作 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
VB   C#

安装

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

dotnet add package IronPdf
dotnet add package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'dotnet add package IronPdf
VB   C#

C# Nameof(开发人员如何使用):图 2 - 使用 NuGet 软件包管理器安装 IronPDF,方法是在 NuGet 软件包管理器的搜索栏中搜索 "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
VB   C#

在这里,IronPDF 使用本地变量 content 和 pdfDocument 生成 PDF,这可以在 PrintPdf 方法中看到。

输出

C# Nameof(开发人员如何使用):图 3 - 程序输出

PDF 生成

C# Nameof(如何为开发人员工作):图 4 - 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"
VB   C#

提供您的电子邮件以获取试用许可证。

结论

C# 的 "nameof "操作符已成为开发人员寻求更简洁、更安全、更可维护代码的主要工具。它能提高代码的可读性,加上编译时安全性和无缝重构支持,使其成为 C# 开发人员工具包中不可或缺的工具。随着开发社区不断接受和利用 "nameof "操作符,它将在塑造 C# 编程的未来中发挥举足轻重的作用。IronPDF 是一个方便的 NuGet 包,可用于快速、轻松地生成 PDF。

< 前一页
C# 操作符(开发人员如何使用)
下一步 >
HashSet C#(它对开发人员的用途)

准备开始了吗? 版本: 2024.9 刚刚发布

免费NuGet下载 总下载量: 10,731,156 查看许可证 >