gpt4 book ai didi

.net - 为什么 Convert.ToInt32 接受 IFormatProvider?

转载 作者:行者123 更新时间:2023-12-03 09:12:14 28 4
gpt4 key购买 nike

在 Convert 类中进行以下重载对我来说是有意义的

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);

关于.net - 为什么 Convert.ToInt32 接受 IFormatProvider?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41241619/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com