如何将nullable int强制转换为nullable short
本文关键字:nullable 转换 short int | 更新日期: 2023-09-27 18:19:31
当我寻找答案时,我得到的命中率指的是从short到int以及从可为null到不可为null的转换。然而,我陷入了如何从"更大"类型int转换的困境转换为"较小"类型短。
我唯一能想到的就是写一个这样的方法:
private short? GetShortyOrNada(int? input)
{
if(input == null)
return (short?)null;
return Convert.ToInt16(input.Value);
}
不过,我希望在一行中完成,因为它只在项目的整个代码库中的一个位置完成,永远不会更改。
简单强制转换有什么问题?我测试了一下,效果很好。
private static short? GetShortyOrNada(int? input)
{
checked//For overflow checking
{
return (short?) input;
}
}
您可以用条件表达式替换条件语句,如下所示:
short? res = input.HasValue ? (short?)Convert.ToInt16(input.Value) : null;
这就是您想要的吗?
private short? GetShortyOrNada(int? input)
{
if(input == null)
return (short?)null;
if(input > Int16.MaxValue)
return Int16.MaxValue;
if(input < Int16.MinValue)
return Int16.MinValue;
return Convert.ToInt16(input.Value);
}
我只是为值过大的情况添加了IF子句。
如果您只想在值不在所需范围内时返回null:
private short? GetShortyOrNada(int? input)
{
if(input == null || input < Int16.MinValue || input > Int16.MaxValue)
return (short?)null;
return Convert.ToInt16(input.Value);
}
希望这会有所帮助。