Determine type from given string input

空扰寡人 提交于 2019-12-11 00:50:45

问题


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!


回答1:


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.

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 :(




回答2:


You got to know something about the expected type. If you do you could use TypeConverter e.g.:

    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.



来源:https://stackoverflow.com/questions/4021115/determine-type-from-given-string-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!