简体   繁体   English

C#的“ nameof”运算符的源代码

[英]Source code for the “nameof” operator of C#

Where can I get the source code for "nameof" of C# or how do I decompile it? 在哪里可以获取C#的“ nameof”源代码或如何对其进行反编译?

I checked https://referencesource.microsoft.com/ , but I couldn't find it. 我检查了https://referencesource.microsoft.com/ ,但找不到。

It's not something you can decompile as such, or show you source code for. 您不能像这样反编译或显示源代码。 It's part of the C# compiler: when you use nameof(Foo) the compiler just injects "Foo" into the source code. 它是C#编译器的一部分:当您使用nameof(Foo) ,编译器仅将“ Foo”注入源代码。 The IL for the methods is exactly the same: 方法的IL 完全相同

static void PrintMyName()
{
    Console.WriteLine(nameof(PrintMyName));
}

vs

static void PrintMyName()
{
    Console.WriteLine("PrintMyName");
}

As noted in comments, it's not just that the name is taken literally as per the operand; 正如评论中所指出的,不仅仅是名称按字面意思按照操作数使用;还包括 it's the last part of the name that's used. 这是所用名称的最后一部分。 So for example, if you have: 因此,例如,如果您有:

string x = "10";
string text = nameof(x.Length);

then that will resolve to "Length". 然后将解析为“长度”。 (This doesn't use the value of x at execution time, either - it's fine if x is null. Or you could use nameof(string.Length) or nameof(String.Length) .) (或者,在执行时不使用x的值-如果x为null很好。或者您可以使用nameof(string.Length)nameof(String.Length) 。)

nameof is a keyword, so you would need to look into the compiler for the source code of how it is processed. nameof是关键字,因此您需要查看编译器以获取如何处理它的源代码。 Fortunately for you, the C# compiler is now open-sourced under the Roslyn project. 对您来说幸运的是,C#编译器现在在Roslyn项目下开源。 Understanding a compiler is not a trivial task – source code is passed through pipelines of transformations, which each one adding more syntactic or semantic information. 了解编译器并不是一件容易的事-源代码通过转换管道传递,每个转换管道都添加了更多的语法或语义信息。 To start you off, the GetContextualKeywordKind parses the nameof keyword into a SyntaxKind.NameOfKeyword , which then gets matched in TryBindNameofOperator . 首先, GetContextualKeywordKindnameof关键字解析为SyntaxKind.NameOfKeyword ,然后在TryBindNameofOperator进行匹配。

As to your other question of creating another such operator: Yes, you can, by cloning and modifying the Roslyn source. 关于创建另一个这样的运算符的另一个问题:是的,您可以通过克隆和修改Roslyn源代码来实现。 However, your new operator would obviously only work on the modified compiler, so you'd need to supply this to whoever will be compiling your code. 但是,您的新运算符显然只能在修改后的编译器上运行,因此您需要将此代码提供给将要编译代码的任何人。 This is something that's rarely done; 这很少做。 you're normally better off defining extension methods for your custom functionality, unless you need something particularly esoteric. 通常,最好为自定义功能定义扩展方法,除非您需要特别深奥的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM