尝试为当前语言设置小数分隔符,获取“Instance is Only Only”

我的代码最初是为英语市场编写的,小数分隔符是“。” 所以它期望数值作为字符串使用“。” 作为分隔符。 但是我们现在在其他地方有用户,例如,小数分隔符为“,”的欧洲地区。

因此,在我的软件(实际上只是当前线程)的上下文中,我想要将当前语言的小数分隔符覆盖为“。”。 即使它默认为其他东西。

我试过了

String sep = "."; NumberFormatInfo nfi1 = NumberFormatInfo.CurrentInfo; nfi1.NumberDecimalSeparator = sep; 

但是我在第三行得到了“ Instance is read-only ”exception。 显然,NumberFormatInfo不可写。 那么如何将当前语言的小数分隔符设置为默认值以外的其他值?

您需要创建新文化,并且可以将当前文化用作模板,并仅更改分隔符。 然后,您必须将当前文化设置为新创建的文化,因为您无法直接更改当前文化中的属性。

 string CultureName = Thread.CurrentThread.CurrentCulture.Name; CultureInfo ci = new CultureInfo(CultureName); if (ci.NumberFormat.NumberDecimalSeparator != ".") { // Forcing use of decimal separator for numerical values ci.NumberFormat.NumberDecimalSeparator = "."; Thread.CurrentThread.CurrentCulture = ci; } 

您可以在NumberFormatInfo实例上使用Clone()方法,该方法将创建一个可变版本(即IsReadOnly = false)。 然后,您可以设置货币符号和/或其他数字格式选项:

 string sep = "."; NumberFormatInfo nfi1 = (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone(); nfi1.NumberDecimalSeparator = sep;