【发布时间】:2012-01-07 17:12:26
【问题描述】:
我很难理解这一点。考虑以下示例:
protected void Page_Load(object sender, EventArgs e)
{
// No surprise that this works
Int16 firstTest = Convert.ToInt16(0);
int firstTest2 = (int)firstTest;
// This also works
object secondTest = 0;
int secondTest2 = (int)secondTest;
// But this fails!
object thirdTest = Convert.ToInt16(0);
int thirdtest2 = (int)thirdTest; // It blows up on this line.
}
我在运行时遇到的具体错误是 Specified cast is not valid. 如果我在 Visual Studio 中快速观看 (int)thirdTest,我会得到 Cannot unbox 'thirdTest' as a 'int' 的值。
这到底是怎么回事?
【问题讨论】:
-
Int16 实际上是一个short。所以我认为你可以替换'Int16 firstTest = Convert.ToInt16(0);' with 'Int16 firstTest = 0s;'
标签: c# c#-4.0 casting boxing unboxing