C# string Parsing to variable types

后端 未结 7 738
暖寄归人
暖寄归人 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:34

    Why can't you use the parsing already available?

    int.Parse("1234");
    decimal.Parse("1234");
    double.Parse("1234");
    

    Or use TryParse if you're not sure it will be able to successfully parse.

    Or if you wanted to implement it as an extension method, take a look at this article that will show you how to create a Generic String.Parse method.

    Edit: I have no idea how that site went down so quickly after I posted my answer. Here is the class that the article created:

    using System;
    using System.ComponentModel;
    
    public static class Parser {
    
         public static T Parse(this string value) {
            // Get default value for type so if string
            // is empty then we can return default value.
            T result = default(T);
    
            if (!string.IsNullOrEmpty(value)) {
              // we are not going to handle exception here
              // if you need SafeParse then you should create
              // another method specially for that.
              TypeConverter tc = TypeDescriptor.GetConverter(typeof(T));
              result = (T)tc.ConvertFrom(value);
            }
    
            return result;
        }
    }
    

    Examples:

    // regular parsing
    int i = "123".Parse(); 
    int? inull = "123".Parse(); 
    DateTime d = "01/12/2008".Parse(); 
    DateTime? dn = "01/12/2008".Parse();
    
    // null values
    string sample = null;
    int? k = sample.Parse(); // returns null
    int l = sample.Parse();   // returns 0
    DateTime dd = sample.Parse(); // returns 01/01/0001
    DateTime? ddn = sample.Parse(); // returns null
    

提交回复
热议问题