int.TryParse = null if not numeric?

前端 未结 8 1458
太阳男子
太阳男子 2021-02-19 10:59

is there some way of return null if it can\'t parse a string to int?

with:

public .... , string? categoryID) 
{
int.TryParse(categoryID, out categoryID);         


        
相关标签:
8条回答
  • 2021-02-19 11:16

    Here's a proper use of Int32.TryParse:

    int? value;
    int dummy;
    if(Int32.TryParse(categoryID, out dummy)) {
        value = dummy;
    }
    else {
        value = null;
    }
    return value;
    
    0 讨论(0)
  • 2021-02-19 11:17

    TryParse will return false if the string can't be parsed. You can use this fact to return either the parsed value, or null. Anyway I guess that you are intending to return int? from your method, then it would be something like this:

    public int? ParseInt(string categoryID) 
    {
        int theIntValue;
        bool parseOk = int.TryParse(categoryID, out theIntValue);
        if(parseOk) {
            return theIntValue;
        } else {
            return null;
        }
    }
    
    0 讨论(0)
  • 2021-02-19 11:19

    How about this?

    public int? ParseToNull(string categoryId)
    {
        int id;
        return int.TryParse(categoryId, out id) ? (int?)id : null;
    }
    
    0 讨论(0)
  • 2021-02-19 11:28

    Int is a value type which means there is no such thing as a null int. So no, TryParse will never alter the out parameter so that it is null.

    But the problem you're having is you're passing a string to the out parameter of TryParse when its expecting an integer.

    You need something like this...

    Int categoryID = 0;
    string strCategoryID = "somestringmaybeitsaninteger";
    
    int.TryParse(strCategoryID, out categoryID);
    
    0 讨论(0)
  • 2021-02-19 11:30

    ** this answer was down-voted a lot ** Although it is a possible solution - it is a bad one performance wise, and probably not a good programming choice.

    I will not delete it, as I guess many programmers might not be aware of this, so here is an example how not to do things:

    use try and catch

    try
    {
    res = Int32.Parse(strVAR)
    }
    catch(exception ex) 
    {
     return null;
    }
    
    0 讨论(0)
  • 2021-02-19 11:32

    Do you want to do something like this?

    public int? Parse(string categoryID) 
    {
      int value;
      if (int.TryParse(categoryID, out value))
      {
        return value;
      }
      else
      {
        return null;
      }
    }
    
    0 讨论(0)
提交回复
热议问题