什么时候使用才有意义int32.Parse(String, IFormatProvider)
?
据我所知, this and无论如何都int32.Parse(String)
使用NumberStyles.Integer
它,它只允许加号、减号或数字,可选地被空格包围,那么为什么语言环境格式会进入等式呢?
我知道千位分隔符,但它们无关紧要,因为NumberStyles.Integer
无论您所在的地区如何,都不允许使用它们。
什么时候使用才有意义int32.Parse(String, IFormatProvider)
?
据我所知, this and无论如何都int32.Parse(String)
使用NumberStyles.Integer
它,它只允许加号、减号或数字,可选地被空格包围,那么为什么语言环境格式会进入等式呢?
我知道千位分隔符,但它们无关紧要,因为NumberStyles.Integer
无论您所在的地区如何,都不允许使用它们。
Consider if you have culture where negative sign is M
(minus). I am pretty sure it doesn't exist but just consider that you have something like that. Then you can do:
string str = "M123";
var culture = new CultureInfo("en-US");
culture.NumberFormat.NegativeSign = "M";
int number = Int32.Parse(str, culture);
This would result in -123
as value. This is where you can use int32.Parse(String, IFormatProvider)
overload. If you don't specify the culture, then it would use the current culture and would fail for the value M123
.
(Old Answer)
It is useful with string with thousand separator
Consider the following example,
string str = "1,234,567";
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE");
int number = Int32.Parse(str, CultureInfo.CurrentCulture);
This would result in an exception since .
is the thousand separator in German culture.
For
int number = Int32.Parse("1.234", NumberStyles.AllowThousands);
The above would parse successfully, since the German culture uses .
as thousand separator.
But if you have current culture set as US then it would give an exception.
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
int number = Int32.Parse("1.234", NumberStyles.AllowThousands);
See: Int32.Parse Method (String, IFormatProvider)
The provider parameter is an IFormatProvider implementation, such as a NumberFormatInfo or CultureInfo object. The provider parameter supplies culture-specific information about the format of s. If provider is null, the NumberFormatInfo object for the current culture is used.
Well how about the thousand separators? I think in USA they use ',' and in Greece they use '.'
USA: 1,000,000 Greece: 1.000.000
万一其他人在 6 年后也对此感到疑惑,那么使用仍然没有意义,Int32.ToString(IFormatProvider?)
或者Int32.Parse(String, IFormatProvider?)
因为更改文化对默认格式和NumberStyles
.
您可以运行这个简单的测试来验证:
using System;
using System.Globalization;
using System.Linq;
class IntToStringTest
{
static void Main()
{
var cultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
var input = -123456789;
var defaultOutput = input.ToString();
var outputCulturePairs = cultures.Select(c => (Output: input.ToString(c), Culture: c));
var parsedOutputs = outputCulturePairs.Select(p => Int32.Parse(p.Output, p.Culture));
Console.WriteLine(outputCulturePairs.All(p => p.Output == defaultOutput));
Console.WriteLine(parsedOutputs.All(o => o == input));
}
}
编辑 8/8/2020:这仅适用于 .NET Framework。在 .NET Core 上,一些阿拉伯文化在值之后使用减号。