.NET 帮助

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

Chipego
奇佩戈-卡琳达
2024年三月6日
分享:

nameof "运算符在 C# 6.0 中引入,是一种编译时构造,旨在解决通过名称引用程序元素和无声地破坏运行时行为的难题。 其主要目的是消除对硬编码字符串的需求,提供一种更易于维护和防错的方法。 在本文中,我们将探讨 C# 中的 nameof 操作符,还将介绍NuGet 上的 IronPDF 库库,以编程方式生成 PDF 文档。

nameof "操作符的基本语法

nameof "操作符的基本语法很简单。 它将元素作为参数,并以字符串形式返回其名称。 考虑以下示例:

static void Main()
{
 //string name
  string myVariable = nameof(myVariable);
}
static void Main()
{
 //string name
  string myVariable = 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.");
}

编译时安全性

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();
    }
}

说明

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

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

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

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

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

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

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

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

介绍IronPDF

IronPDF for C#.NET是一个 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");
    }
}

安装

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

dotnet add package IronPdf
dotnet add package IronPdf

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();
    }
}

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

输出

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

PDF 生成

C# Nameof(如何为开发人员工作):图 4 - PDF 输出

许可(可免费试用)

有关许可,请查看试用许可信息. 这个密钥需要放置在appsettings.json中。

"IronPdf.LicenseKey": "your license key"
"IronPdf.LicenseKey": "your license key"

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

结论

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

Chipego
软件工程师
Chipego 拥有出色的倾听技巧,这帮助他理解客户问题并提供智能解决方案。他在 2023 年加入 Iron Software 团队,此前他获得了信息技术学士学位。IronPDF 和 IronOCR 是 Chipego 主要专注的两个产品,但他对所有产品的了解每天都在增长,因为他不断找到支持客户的新方法。他喜欢 Iron Software 的合作氛围,公司各地的团队成员贡献他们丰富的经验,以提供有效的创新解决方案。当 Chipego 离开办公桌时,你经常可以发现他在看书或踢足球。
< 前一页
C# 操作符(开发人员如何使用)
下一步 >
HashSet C#(它对开发人员的用途)