如何使用类型转换器转换成具体的双重文化?转换器、转换成、如何使用、具体

2023-09-04 00:17:17 作者:逆臣

我与类型转换器类的问题。它的工作原理罚款与 CultureInvariant 值,但不能将特定的文化如英语千位分隔符。下面是一个小的测试程序,我不能去上班。

I have a problem with the TypeConverter class. It works fine with CultureInvariant values but cannot convert specific cultures like English thousands separators. Below is a small test program that I cannot get to work.

这里的问题:) - 2,999.95不是双有效值 ConvertFromString 与下面的消息会引发异常的 的并用内部异常的输入字符串的不正确的格式。的。

Here's the problem :) - ConvertFromString throws an exception with the following message "2,999.95 is not a valid value for Double." and with the inner exception "Input string was not in a correct format.".

using System;
using System.Globalization;
using System.ComponentModel;

class Program
{
    static void Main()
    {
        try
        {
            var culture = new CultureInfo("en");
            var typeConverter = TypeDescriptor.GetConverter(typeof(double));
            double value = (double)typeConverter.ConvertFromString(
                null, 
                culture, 
                "2,999.95");

            Console.WriteLine("Value: " + value);
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
    }
}

编辑: 链接到连接

Link to the bug report on Connect

推荐答案

DoubleConverter TypeDescriptor.GetConverter中获得的(typeof运算(双) )结束跌宕调用 Double.Parse 以下参数:

The DoubleConverter that is obtained from TypeDescriptor.GetConverter(typeof(double)) end ups calling Double.Parse with the following arguments:

Double.Parse(
    "2,999.95", 
    NumberStyles.Float, 
    (IFormatProvider)culture.GetFormat(typeof(NumberFormatInfo)));

问题是, NumberStyles.Float 不会让千位分隔符,这就是为什么你所得到的问题。您可以在 Microsoft连接提出这样或看其他人有同样的问题。

The problem is that NumberStyles.Float does not allows thousands separators and that's why you are getting the problem. You can submit this on Microsoft Connect or see if anybody else had the same problem.

如果 Double.Parse 被称为还与 NumberStyles.AllowThousands 不会出现问题。

If Double.Parse is called also with NumberStyles.AllowThousands the problem would not occur.

Double.Parse(
    "2,999.95", 
    NumberStyles.Float | NumberStyles.AllowThousands, 
    (IFormatProvider)culture.GetFormat(typeof(NumberFormatInfo)));