nameof(ServiceResult<object>.Result)
, ServiceResult<object>
我的自定义类型在哪里,是Result
这种类型的字段。ServiceResult<object>
只是类型的声明,它没有运算符 new 和 (),但 MS 的官方页面说nameof
接受变量及其成员。为什么这个表达有效?我以前没有看到这样的声明。
问问题
106 次
1 回答
5
您提到的规范可能是旧的,C# 6.0nameof
运算符参考:
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/nameof
to 的参数
nameof
必须是简单名称、限定名称、成员访问权限、具有指定成员的基本访问权限或具有指定成员的此访问权限。参数表达式标识代码定义,但从不计算。
在你的情况下,它是一个表达式。如同
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"
于 2018-03-23T07:57:20.740 回答