【发布时间】:2015-06-02 17:04:57
【问题描述】:
C#6 中的字符串插值让我可以这样写:
decimal m = 42.0m;
string x = $"The value is {m}";
但是,字符串格式化的一个非常常见的用例是指定用于格式化值的语言环境。假设我需要使用InvariantCulture 进行上面的格式化操作,它的语法是什么?
This discussion 建议我应该可以这样做:
string x = INV($"The value is {m}");
INV定义为
public static string INV(IFormattable formattable)
{
return formattable.ToString(null, System.Globalization.CultureInfo.InvariantCulture);
}
但是,这不起作用。它可以编译,但它让我的程序在启动时挂在 cmd.exe 中 - 好像我假设正在调用的 klr.exe 挂起(编译器错误?)
这是 VS15 CTP 6 中的 ASP.NET 5 控制台项目。
【问题讨论】:
-
@KeithHill 字符串插值的默认值是当前文化不是不变的。 :(
-
@AaronStainback 是的,谢谢。我后来注意到了,但忘了回来更正我的评论。
-
@Aaron:在那种情况下,你有没有解释为什么我总是得到这个错误:(VS2015 中的 C# Framwork 4.6 项目):
CA1305 (Because the behavior of 'string.Format(string, object, object)' could vary based on the current user's locale settings, replace this call in 'Function()' with a call to 'string.Format(IFormatProvider, string, params object[])'. If the result of 'string.Format(IFormatProvider, string, params object[])' will be displayed to the user, specify 'CultureInfo.CurrentCulture' as the 'IFormatProvider' parameter[...] -
@eFloh 使用未指定区域性信息的
string.Format重载时会出现代码分析错误的原因相同。此代码分析规则的重点是强制您明确指定文化信息,因为开发人员很容易在需要时忽略将其标记为不变量(或错误地假设不变量是默认文化) -
好的,这是有道理的。在这种情况下,我们需要一种很酷的语法来指定插值字符串的区域性,例如 $(CultureInfo.CurrentCulture)"my {interpolated} string" 或至少 Current(..) 就像现有的 INV(.. .)
标签: c# roslyn c#-6.0 string-interpolation