int.TryParse syntatic sugar

后端 未结 10 1394
广开言路
广开言路 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.

提交回复
热议问题