为什么Convert.ToInt32接受IFormatProvider?

时间:2016-12-20 11:46:21

标签: .net number-formatting cultureinfo

在转换类

中有以下重载是有道理的
public static double ToDouble(string value, IFormatProvider provider);

的示例:

Console.WriteLine(Convert.ToDouble("3223.2", CultureInfo.InvariantCulture)); // success
Console.WriteLine(Convert.ToDouble("3223,2", new CultureInfo("fr-FR"))); // success
Console.WriteLine(Convert.ToDouble("3223.2", new CultureInfo("fr-FR"))); // failure

但是使用以下重载的例子是什么?

public static int ToInt32(string value, IFormatProvider provider);

下面的一切都失败了:

Console.WriteLine(Convert.ToInt32("3223.2", CultureInfo.InvariantCulture));
Console.WriteLine(Convert.ToInt32("3223,2", new CultureInfo("fr-FR")));
Console.WriteLine(Convert.ToInt32("3223.2", new CultureInfo("fr-FR")));

换句话说,是否存在整数(在任何文化中)的有效字符串表示形式,如果不指定IFormatProvider,则无法将其转换为int?

1 个答案:

答案 0 :(得分:2)

当您使用简单版本的Convert.ToInt32时,您仍然使用带有只读CultureInfo.CurrentCulture的重载,如您查看reference source of Convert.ToInt32

所示
public static int ToInt32(String value) {
    if (value == null)
        return 0;
    return Int32.Parse(value, CultureInfo.CurrentCulture);
}

关键是,许多文化,无论是否定制,都可以使用不同的字符进行常规操作,如转换,需要适当的支持结构。

这是一个奇怪的自定义CultureInfo使用示例,它允许将字符串奇怪地转换为整数

CultureInfo ci = new CultureInfo("it-IT");
ci.NumberFormat.NegativeSign = "@";

int number = Convert.ToInt32("@10", ci);
Console.WriteLine(number);