C# string Parsing to variable types

后端 未结 7 717
暖寄归人
暖寄归人 2021-02-02 04:55

I want to parse a string into a type easily, but I don\'t want to write wrapper code for each type, I just want to be able to do \"1234\".Parse() or the like and have it return

相关标签:
7条回答
  • 2021-02-02 05:35

    I know this question is four years old, but still you could consider using this:

    public static T Parse<T>(this string target)
    {
        Type type = typeof(T);
    
        //In case of a nullable type, use the underlaying type:
        var ReturnType = Nullable.GetUnderlyingType(type) ?? type;
    
        try
        {
            //in case of a nullable type and the input text is null, return the default value (null)
            if (ReturnType != type && target == null)
                return default(T);
    
            return (T)Convert.ChangeType(target, ReturnType);
        }
        catch
        {
            return default(T);
        }
    }
    
    0 讨论(0)
提交回复
热议问题