"nameof " 运算符,"expression cannot be used in an argument to nameof"

The "nameof " operator,"expression cannot be used in an argument to nameof"

我得到了一个简单的 class:

public class Stu
{
    public string Name { get; set; }
}

如果我这样做:

var stu = new Stu();
Console.WriteLine(nameof(stu.Name));

效果很好。 但是这个:

Console.WriteLine(nameof(new Stu().Name));

或者这个:

Console.WriteLine(nameof((new Stu()).Name));

不工作,编译器告诉我:"expression cannot be used in an argument to nameof"。

我不知道why.What提示是什么意思?运算符的正确参数类型是什么"nameof()"?

我在网上搜索,this 页面告诉我 "expression may be a property-group or a method-group",但是表达式 "new Stu().Name" 不是 "property-group" 吗?

你可能想要

nameof(Stu.Name)

nameof() 获得一些特殊语法,因此您不必实例化 class 来获取其属性之一的名称,以及其他类似情况。