Does C# 6.0's String interpolation rely on Reflection?

隐身守侯 提交于 2019-12-08 17:02:10

问题


Short and simple. Does the new string interpolation in C# 6.0 rely on reflection? I.e. does

string myStr = $"Hi {name}, how are you?";

use reflection at runtime to find the variable "name" and its value?


回答1:


No. It doesn't. It is completely based on compile-time evaluation.

You can see that with this TryRoslyn example that compiles and decompiles this:

int name = 4;
string myStr = $"Hi {name}, how are you?";

Into this:

int num = 4;
string.Format("Hi {0}, how are you?", num);

string interpolation also supports using IFormattable as the result so (again using TryRoslyn) this:

int name = 4;
IFormattable myStr = $"Hi {name}, how are you?";

Turns into this:

int num = 4;
FormattableStringFactory.Create("Hi {0}, how are you?", new object[] { num });



回答2:


This article explains that it's compile-time based (and internally calls string.Format(). A quote:

String interpolation is transformed at compile time to invoke an equivalent string.Format call. This leaves in place support for localization as before (though still with composite format strings) and doesn’t introduce any post compile injection of code via strings.



来源:https://stackoverflow.com/questions/31359360/does-c-sharp-6-0s-string-interpolation-rely-on-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!