代码之家  ›  专栏  ›  技术社区  ›  Robin Maben

根据给定的字符串输入确定类型

  •  2
  • Robin Maben  · 技术社区  · 14 年前

    如:

    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.
    

    我必须从头开始写吗?
    只是想在我开始之前看看有没有人知道更好的方法。

    2 回复  |  直到 14 年前
        1
  •  7
  •   Jon Skeet    14 年前

    我很确定你必须从头开始写这篇文章,部分原因是 非常

    我想我从来没有遇到过类似的事情——老实说,这种猜测通常会让我紧张。即使知道数据类型,也很难正确地进行解析,更不用说在猜测要开始的数据类型时:(

        2
  •  7
  •   Amittai Shapira    14 年前

    如果需要,您可以使用类型转换器,例如:

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

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