我很难理解这一点。考虑以下示例:
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 中使用 QuickWatch (int)thirdTest
,我得到的值是 无法将“thirdTest”拆箱为“int”
。
这到底是怎么回事?
最佳答案
拆箱检查确切类型,如 documentation 中所述.
Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value type that implements the interface. An unboxing operation consists of:
Checking the object instance to make sure that it is a boxed value of the given value type.
Copying the value from the instance into the value-type variable.
如您所见,第一步是检查对象实例是否与目标类型匹配。
另引自文档:
For the unboxing of value types to succeed at run time, the item being unboxed must be a reference to an object that was previously created by boxing an instance of that value type. Attempting to unbox null causes a NullReferenceException. Attempting to unbox a reference to an incompatible value type causes an InvalidCastException.
因此,要修复此错误,请确保在尝试拆箱之前类型匹配:
object thirdTest = Convert.ToInt16(0);
short thirdtest2 = (short)thirdTest;
关于C# - 装箱/拆箱/类型转换整数的问题。我不明白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8771476/