C# 6.0 的字符串插值是否依赖于反射?
Does C# 6.0's String interpolation rely on Reflection?
简短。 C# 6.0 中新的字符串插值是否依赖于反射? IE。确实
string myStr = $"Hi {name}, how are you?";
在运行时使用反射来查找变量 "name" 及其值?
没有。它没有。它完全基于编译时评估。
你可以看到用这个 TryRoslyn example 编译和反编译这个:
int name = 4;
string myStr = $"Hi {name}, how are you?";
进入这个:
int num = 4;
string.Format("Hi {0}, how are you?", num);
字符串插值也支持使用 IFormattable
作为结果所以 (again using TryRoslyn) this:
int name = 4;
IFormattable myStr = $"Hi {name}, how are you?";
变成这样:
int num = 4;
FormattableStringFactory.Create("Hi {0}, how are you?", new object[] { num });
This article 解释说它是基于编译时的(并在内部调用 string.Format()
。引用:
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.
简短。 C# 6.0 中新的字符串插值是否依赖于反射? IE。确实
string myStr = $"Hi {name}, how are you?";
在运行时使用反射来查找变量 "name" 及其值?
没有。它没有。它完全基于编译时评估。
你可以看到用这个 TryRoslyn example 编译和反编译这个:
int name = 4;
string myStr = $"Hi {name}, how are you?";
进入这个:
int num = 4;
string.Format("Hi {0}, how are you?", num);
字符串插值也支持使用 IFormattable
作为结果所以 (again using TryRoslyn) this:
int name = 4;
IFormattable myStr = $"Hi {name}, how are you?";
变成这样:
int num = 4;
FormattableStringFactory.Create("Hi {0}, how are you?", new object[] { num });
This article 解释说它是基于编译时的(并在内部调用 string.Format()
。引用:
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.