C#中的 nameof 操作符
C#中的 nameof 操作符用于返回一个字符串,表示指定表达式的名称。
语法
<code>nameof(expression)</code>
其中,
expression可以是以下任何一种: 字段 属性 方法 事件 类型 类型成员(例如,字段、属性、方法等)
作用
nameof 操作符在以下情况下非常有用:
在字符串连接中使用变量或成员名称。 在错误消息或日志输出中包含变量或成员名称。 通过反射获取成员的信息。 生成动态代码或元数据。示例
<code class="csharp">// 字段
int age = 25;
Console.WriteLine($"My age is {nameof(age)}");
// 属性
string name = "John";
Console.WriteLine($"My name is {nameof(name)}");
// 方法
void PrintName() { Console.WriteLine("John"); }
Console.WriteLine($"The method name is {nameof(PrintName)}");
// 类型
Console.WriteLine($"The type name is {nameof(int)}");</code>输出
<code>My age is age My name is name The method name is PrintName The type name is Int32</code>
注意
nameof 操作符不能用于:
局部变量 匿名类型 动态类型