在C#中强制转换短值为int的对象
本文关键字:int 对象 转换 | 更新日期: 2023-09-27 18:23:50
考虑以下代码:
private static void Main(string[] args)
{
short age = 123;
object ageObject = age;
//var intAge = (int)ageObject;//Specified cast is not valid.
int newAge= (short)intAge;
Console.ReadLine();
}
我必须给object分配一个短值,然后再次强制转换为int,但当我尝试这样做时:var intAge = (int)ageObject;
我得到:指定的强制转换无效。我不知道为什么?
在谷歌中搜索后,我发现应该转换为short并分配给int:int newAge= (short)intAge;
为什么我们应该强制转换为short并赋值给int?
编译器为什么会有这种行为?
故障是运行时错误。
原因是age
值已被装箱到一个对象中;将其取消装箱为不正确的类型(int
)是失败的——它是short
。
您注释掉的行上的强制转换是一个取消装箱操作,而不仅仅是强制转换。
使用
Convert.ToInt32(ageObject) instead.
它将工作
我不明白为什么要将short转换为object,然后再转换为int。
您可以通过以下方式进行short->int转换:
{
short age = 123;
int intAge1 = (short)age;
int intAge2 = (int)age;
int intAge3 = Int16.Parse(age.ToString());
}
装箱的值只能取消装箱到完全相同类型的变量这种限制有助于速度优化,使.NET1.x在泛型出现之前变得可行。看看这个
简单的值类型实现IConvertable接口。通过使用Convert类调用
short age= 123;
int ix = Convert.ToInt32(age);