C# 将int转换为short的更好方法?(如果不可能,则为空)
我有以下两种方法将C# 将int转换为short的更好方法?(如果不可能,则为空),c#,.net,C#,.net,我有以下两种方法将int转换为short? 如果值不在短范围内,则第一个失败 第二种方法可以工作,但它有一个不必要的到字符串的转换 有更好的方法吗 编辑: 从下面的答案可以看出: Int16只是Int32的一个子集,因此不需要任何到“中间”类型的转换 代码 //Approach 1 int vIn = 123456789; short? vOut = Convert.ToInt16(vIn); //Value was either too large or too small for an In
int
转换为short?
到字符串的转换
//Approach 1
int vIn = 123456789;
short? vOut = Convert.ToInt16(vIn);
//Value was either too large or too small for an Int16.
//Approach 2
short? vOut2 = null;
int vIn2 = 123456789;
short number;
string characterRepresentationOfInt = vIn2.ToString();
bool result = Int16.TryParse(characterRepresentationOfInt, out number);
if (result)
{
vOut2 = number;
}
参考:
为什么不能简单地使用cast的内置转换?只需添加一个检查以确保它不超出范围(如果您希望使用
null
值而不是异常)
short?ConvertToSort(int值)
{
if(值Int16.MaxValue)
返回null;
返回(短)值;
}
关于你的方法:
null
值,如果value
超出Int16
的有效范围,则转换可能会失败Int16
只是Int32
的一个子集,因此不需要任何到“中间”类型的转换这里有几个可能的解决方案 静态辅助方法:
public static class Number
{
public static bool TryConvertToShort(int value, out short result)
{
bool retval = false;
result = 0;
if (value > Int16.MinValue && value < Int16.MaxValue)
{
result = Convert.ToInt16(value);
retval = true;
}
return retval;
}
}
扩展方法:
public static class ExtendInt32
{
public static bool TryConvertToShort(this int value, out short result)
{
bool retval = false;
result = 0;
if (value > Int16.MinValue && value < Int16.MaxValue)
{
result = Convert.ToInt16(value);
retval = true;
}
return retval;
}
}
您还可以创建一个不会正常失败的帮助器/扩展方法,而是返回默认值(0)或引发异常
short? ConvertToShort(int value)
{
if (value < Int16.MinValue || value > Int16.MaxValue)
return null;
return (short)value;
}
public static short ConvertToShort(int value)
{
short result;
if (value > Int16.MinValue && value < Int16.MaxValue)
{
result = Convert.ToInt16(value);
}
else
{
throw new OverflowException();
}
return result;
}
公共静态短转换器端口(int值)
{
短期结果;
if(value>Int16.MinValue&&value
是的。。。。“Int16只是Int32的一个子集,所以您不需要任何到“中间”类型的转换。”这是我遗漏的关键点。。。非常感谢。@AdrianoRepetti对不起,我把评论贴错了答案。没关系,我没有投反对票。。。我也不认为有任何理由投反对票。。。[我实际上投了赞成票]让我猜一下:如果超出范围,他会要求一个空值,Convert.ToInt16()会自动抛出OverflowException。也就是说,在适用的情况下,我更喜欢使用TryConvert方法返回null值。可为null的short只不过是short和bool,那么为什么不只返回其中一个呢?为什么使用>和<而不是>=和
int a = 1234;
short b;
bool success = a.TryConvertToShort(out b);
public static short ConvertToShort(int value)
{
short result;
if (value > Int16.MinValue && value < Int16.MaxValue)
{
result = Convert.ToInt16(value);
}
else
{
throw new OverflowException();
}
return result;
}