简体   繁体   English

是否将c#6.0 nameof()结果实现了?

[英]Is c# 6.0 nameof() result interned?

From what I can read the compiler just emits a string and nothing else really happens? 从我可以读到的编译器只发出一个字符串,没有其他真正发生?

Is there any reason that the results of this call couldn't be interned? 有没有理由说这个电话会议的结果无法实现? For a nameof(MyClass) , if it happens a lot, it could, theoretically be worth it? 对于nameof(MyClass) ,如果它发生了很多,理论上它可能值得吗?

Yes, it will be interned just as any other string literal. 是的,它将像任何其他字符串文字一样被实习。

This can be demonstrated with this TryRoslyn example where this: 这可以通过这个TryRoslyn示例来演示,其中:

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

Is complied into this IL: 符合此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

You can see that "M" is being loaded using ldstr which means it is interned: 您可以看到使用ldstr加载"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")." “公共语言基础结构(CLI)保证引用具有相同字符序列的两个元数据标记的两个ldstr指令的结果精确地返回相同的字符串对象(称为”字符串实习“的过程)。

From OpCodes.Ldstr Field 来自OpCodes.Ldstr Field

This can also be verified by running this example, which prints true : 这也可以通过运行此示例来验证,该示例打印为true

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

If the compiled output is a string literal, it will be interned. 如果编译的输出是字符串文字,它将被实习。 String literals are interned in .NET runtime. 字符串文字在.NET运行时中实现。

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

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