int.TryParse = null if not numeric?

前端 未结 8 1460
太阳男子
太阳男子 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: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;
        }
    }
    

提交回复
热议问题