从给定的字符串输入确定类型

Rob*_*ben 2 .net c# string types .net-4.0

有没有办法从给定的字符串输入中检测类型?

例如:

string input = "07/12/1999";

string DetectType( s ) { .... }

Type t = DetectType(input); // which would return me the matched datatype. i.e. "DateTime" in this case.
Run Code Online (Sandbox Code Playgroud)

我是否必须从头开始写这个?
只是想在我开始之前检查是否有人知道更好的方法.

谢谢!

Jon*_*eet 7

我敢肯定,你就必须从头开始写这-部分是因为它的将是非常严格根据您的要求.即使是一个简单的问题,例如你给出的日期是12月7日还是7月12日,这里可以产生很大的不同......以及你的日期格式是否严格,你需要支持的数字格式等等.

我不认为我曾经遇到过类似的东西 - 说实话,这种猜测通常会让我感到紧张.即使您知道数据类型,也很难正确解析,更不用说当您猜测数据类型时:(

  • 那是Jon Skeet爵士在说话. (3认同)

Ami*_*ira 7

你必须了解预期的类型.如果你这样做,你可以使用TypeConverter,例如:

    public object DetectType(string stringValue)
    {
        var expectedTypes = new List<Type> {typeof (DateTime), typeof (int)};
        foreach (var type in expectedTypes)
        {
            TypeConverter converter = TypeDescriptor.GetConverter(type);
            if (converter.CanConvertFrom(typeof(string)))
            {
                try
                {
                    // You'll have to think about localization here
                    object newValue = converter.ConvertFromInvariantString(stringValue);
                    if (newValue != null)
                    {
                        return newValue;
                    }
                }
                catch 
                {
                    // Can't convert given string to this type
                    continue;
                }

            }  
        }

        return null;
    }
Run Code Online (Sandbox Code Playgroud)

大多数系统类型都有自己的类型转换器,您可以使用类上的TypeConverter属性编写自己的类型转换器,并实现自己的转换器.