int.TryParse syntatic sugar

后端 未结 10 1389
广开言路
广开言路 2020-12-14 14:15

int.TryPrase is great and all, but there is only one problem...it takes at least two lines of code to use:

int intValue;
string stringValue = \"         


        
相关标签:
10条回答
  • 2020-12-14 14:47

    Maybe use an extension method:

    public static class StringExtensions
    {
        public static int TryParse(this string input, int valueIfNotConverted)
        {
            int value;
            if (Int32.TryParse(input, out value))
            {
                return value;
            }
            return valueIfNotConverted;
        }
    }
    

    And usage:

    string x = "1234";
    int value = x.TryParse(0);
    

    Edit: And of course you can add the obvious overload that already sets the default value to zero if that is your wish.

    0 讨论(0)
  • 2020-12-14 14:49

    You do not WANT to make int.TryParse() one line. Why? Because you can't make an assignment to intValue if the input string isn't a valid integer. The whole point of TryParse() is to allow you to test for good input and degrade gracefully, rather than having to catch an exception.

    Int.TryParse() is already a shortcut so you don't have to test for a valid int and do the assignment in two steps... that's as far as you want to take it.

    0 讨论(0)
  • 2020-12-14 14:51

    I would create an extension method out of this.

        public static int? AsInt32(this string s)
        {
            int value;
            if (int.TryParse(s, out value))
                return value;
    
            return null;
        }
    
    0 讨论(0)
  • 2020-12-14 14:52
    int val2 = "asd".AsInt(-1); 
    //Output : -1
     int val3 = "123".AsInt(-1); 
    //Output : 123
    

    You need to have System.Web.WebPages namespace.

    0 讨论(0)
提交回复
热议问题