nameof(ServiceResult<object>.Result)
,其中ServiceResult<object>
是我的自定义类型和 Result
是该类型的字段。 ServiceResult<object>
只是类型的声明,它没有运算符 new 和 (),但是 MS 的官方页面显示 nameof
接受变量及其成员。 为什么这个表达式有效?我以前没有看到过这样的声明。
最佳答案
您提到的规范可能是旧规范,C# 6.0 nameof
运算符引用:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/nameof
The argument to
nameof
must be a simple name, qualified name, member access, base access with a specified member, or this access with a specified member. The argument expression identifies a code definition, but it is never evaluated.
在你的例子中,它是一个表达式。类似于
nameof(C.Method2) -> "Method2"
来自该文章中的示例列表。
示例
using Stuff = Some.Cool.Functionality
class C {
static int Method1 (string x, int y) {}
static int Method1 (string x, string y) {}
int Method2 (int z) {}
string f<T>() => nameof(T);
}
var c = new C()
nameof(C) -> "C"
nameof(C.Method1) -> "Method1"
nameof(C.Method2) -> "Method2"
nameof(c.Method1) -> "Method1"
nameof(c.Method2) -> "Method2"
nameof(z) -> "z" // inside of Method2 ok, inside Method1 is a compiler error
nameof(Stuff) = "Stuff"
nameof(T) -> "T" // works inside of method but not in attributes on the method
nameof(f) -> "f"
nameof(f<T>) -> syntax error
nameof(f<>) -> syntax error
nameof(Method2()) -> error "This expression does not have a name"
关于c# - 为什么这个表达式有效? (C#6.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49444768/