c# 6.0 nameof() 结果是否被实习?

Is c# 6.0 nameof() result interned?

据我所知,编译器只发出一个字符串,实际上没有发生任何其他事情?

是否有任何原因无法保留此调用的结果?对于一个 nameof(MyClass),如果它经常发生,理论上是值得的吗?

如果编译后的输出是字符串字面量,它将被驻留。字符串文字驻留在 .NET 运行时中。

是的,它将像任何其他字符串文字一样被驻留。

这可以用 this TryRoslyn example 来证明,其中:

public void M() 
{
    Console.WriteLine(nameof(M));
}

被编译到这个 IL:

.method public hidebysig 
    instance void M () cil managed 
{
    // Method begins at RVA 0x2050
    // Code size 11 (0xb)
    .maxstack 8

    IL_0000: ldstr "M"
    IL_0005: call void [mscorlib]System.Console::WriteLine(string)
    IL_000a: ret
} // end of method C::M

您可以看到 "M" 正在使用 ldstr 加载,这意味着它已被驻留:

"The Common Language Infrastructure (CLI) guarantees that the result of two ldstr instructions referring to two metadata tokens that have the same sequence of characters return precisely the same string object (a process known as "string interning")."

来自OpCodes.Ldstr Field

这也可以通过 运行 这个例子来验证,它打印 true:

Console.WriteLine(ReferenceEquals(nameof(Main), nameof(Main)));