c# - 为什么这个表达式有效? (C#6.0)

标签 c# c#-6.0 nameof

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/

相关文章:

c# - 在 C# 中创建 <base class> 类型的变量来存储 <derived class> 对象

c# - 在构建过程中C#6 nameof是否得到优化?

c# - 我应该提供一个带有 nameof 成员名称的方法,还是应该依赖 CallerMemberName 来为我做这件事?

java - Java 中的等价名称

c# - 只调用单一依赖方法的单元测试方法 - c#/xUnit/Moq

c# - MVC 2 : How to use Html. 下拉列表?

c# - 快速流畅地滚动图像

c# - 可以对值类型强制执行 [Required]

c# - 为一个 Windows 用户生成唯一 key

c# - 获取作为参数传递的变量的原始名称?