简体   繁体   English

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

[英]Determine type from given string input

Is there any way to detect the type from a given string input? 有没有办法从给定的字符串输入中检测类型?

Eg: 例如:

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.

Would I have to write this from scratch? 我是否必须从头开始写这个?
Just wanted to check if anybody knows of a better way before I went about it. 只是想在我开始之前检查是否有人知道更好的方法。

Thanks! 谢谢!

I'm pretty sure you'll have to write this from scratch - partly because it's going to be very strictly tailored to your requirements. 我敢肯定,你就必须从头开始写这-部分是因为它会非常严格地根据您的要求。 Even a simple question such as whether the date you've given is December 7th or July 12th can make a big difference here... and whether your date formats are strict, what number formats you need to support etc. 即使是一个简单的问题,例如你给出的日期是12月7日还是7月12日,这里可以产生很大的不同......以及你的日期格式是否严格,你需要支持的数字格式等等。

I don't think I've ever come across anything similar - and to be honest, this sort of guesswork usually makes me nervous. 我不认为我曾经遇到过类似的东西 - 说实话,这种猜测通常会让我感到紧张。 It can be hard to get parsing right even when you know the data type, let alone when you're guessing at the data type to start with :( 即使您知道数据类型,也很难正确解析,更不用说当您猜测数据类型时:(

You got to know something about the expected type. 你必须了解预期的类型。 If you do you could use TypeConverter eg: 如果你这样做,你可以使用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;
    }

Most system types have their own type converter, and you could write your own using the TypeConverter attribute on your class, and implementing your own converter. 大多数系统类型都有自己的类型转换器,您可以使用类上的TypeConverter属性编写自己的类型转换器,并实现自己的转换器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM