Is it possible to use operator ?? and throw new Exception()?

前端 未结 5 1996
挽巷
挽巷 2020-12-17 08:43

I have a number of methods doing next:

var result = command.ExecuteScalar() as Int32?;
if(result.HasValue)
{
   return result.Value;
}
else
{
   throw new Ex         


        
5条回答
  •  不知归路
    2020-12-17 09:02

    If you just want an exception when the returned value isn't an Int32 then do this:

    return (int)command.ExecuteScalar();
    

    If you want to throw your own custom exception then I'd probably do something like this instead:

    int? result = command.ExecuteScalar() as int?;
    if (result == null) throw new YourCustomException();
    return result.Value;
    

提交回复
热议问题