int.TryParse = null if not numeric?

2020-07-03 07: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);

getting "cannot convert from 'out string' to 'out int'

what to do?

EDIT:

No longer relevant because of asp.net constraints is the way to solve problem

/M

标签: c# .net tryparse
8条回答
三岁会撩人
2楼-- · 2020-07-03 08:36

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;
  }
}
查看更多
地球回转人心会变
3楼-- · 2020-07-03 08:37

** 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;
}
查看更多
登录 后发表回答