Dynamic TryParse for all data types

后端 未结 3 508
小蘑菇
小蘑菇 2020-12-21 06:39

I have the need to examine to see if an object can be converted to a specific DataType or not, and came up with this :

public static bool TryParseAll(System         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-21 07:32

    You should use the TypeDescriptor class:

    public static T Convert(this string input)
    {
        var converter = TypeDescriptor.GetConverter(typeof(T));
        if(converter != null)
        {
            //Cast ConvertFromString(string text) : object to (T)
            return (T)converter.ConvertFromString(input);
        }
        return default(T);
    }
    

    of course this will throw an exception if the conversion fails so you will want to try/catch it.

提交回复
热议问题