如何将nullable int转换为可空的short?

Kon*_*ten 3 c# int nullable short type-conversion

当我寻找答案时,我得到的命中是指从short转换int,从nullable转换为not-null.但是,我陷入了如何从"更大"类型int转换到"小"型短?.

我能想到的唯一方法是编写一个这样的方法:

private short? GetShortyOrNada(int? input)
{
  if(input == null)
    return (short?)null;
  return Convert.ToInt16(input.Value);
}
Run Code Online (Sandbox Code Playgroud)

不过,我希望在一行中做到这一点,因为它只在项目的整个代码库中完成了一个地方,并且不会有任何变化.

Sri*_*vel 11

简单演员有什么问题?我测试过,运行正常.

private static short? GetShortyOrNada(int? input)
{
    checked//For overflow checking
    {
        return (short?) input;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 得爱"解除"运营商 (3认同)