C# 中的 nameof 表达式
Muhammad Maisam Abbas
2023年10月12日

本教程将讨论 C# 中 nameof
表达式的用法。
C# 中的 nameof
表达式
nameof
表达式获取 C# 中变量的名称,数据类型、字段或成员。nameof
表达式将工件作为输入,并以字符串格式返回该特定工件的名称。在下面的代码示例中对此进行了说明。
using System;
namespace nameof_operator {
class Program {
static void Main(string[] args) {
int number = 15;
Console.WriteLine(nameof(number));
Console.WriteLine(nameof(System.Int32));
Console.WriteLine(nameof(nameof_operator));
}
}
}
输出:
number
Int32
nameof_operator
我们在 C# 中使用 nameof
表达式打印了变量的名称,数据类型和名称空间。nameof
表达式在编译时被求值,并且在运行时不影响处理速度。nameof
表达式的主要用途是在检查 ArgumentException
及其相关内容的参数中。例如,如果我们有一个名为 data
的变量,并且正在显示一条消息,说明如果 data
变量为空,则不会初始化。在常规程序中它可以正常工作,但是如果将 data
变量的名称更改为 input
变量,我们还必须更改输出消息。只需使用一个 nameof
表达式即可很好地处理这种情况,如下面的编码示例所示。
public string getData(int data) {
if (data == null) {
throw new ArgumentNullException(nameof(data));
}
}
现在,我们不必担心更改大量代码将 data
变量重命名为其他名称的情况。
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn