为什么 Convert.ToInt32 接受 IFormatProvider?
Why does Convert.ToInt32 accept IFormatProvider?
在 Convert class
中进行以下重载对我来说很有意义
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?
当您使用 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);
在 Convert class
中进行以下重载对我来说很有意义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?
当您使用 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);