Convert.ToInt16和(Int16)有什么区别 [英] what is difference between Convert.ToInt16 and (Int16)

查看:152
本文介绍了Convert.ToInt16和(Int16)有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一段代码

try
{
  object s = new object();
  s = 10;
  Console.WriteLine("{0}", Convert.ToInt16(s));
  Console.WriteLine("{0}", (Int16)s);
}
catch (InvalidCastException ex)
{
  Console.WriteLine(ex.Message);
  Console.ReadLine();
}

在此基础上,我有很多疑问。.

1)是Convert.ToInt16()和(Int16)都是取消装箱操作

2)如果两者都与取消装箱相关,那么为什么它们不同。因为上面的代码在遵循 Console.WriteLine( {0},(Int16)s); 行时显示以下错误

错误:

指定的转换无效

3)据我所知,(Int16)是常规转换和 Convert.ToInt16()是类型安全的转换。但是什么使这些在这里不同呢?
也许这是一个愚蠢的问题,但我很困惑。请为我澄清这一点,并在错误之处纠正我。

on the basis of which I have lots of questions..
1) Is Convert.ToInt16() and (Int16) both are Unboxing operations
2) If both are related to Unboxing then why they are different. Because the above code shows the following error when Console.WriteLine("{0}", (Int16)s); line is complied
Error:
Specified cast is not valid
3) As i know (Int16) is conventional casting and Convert.ToInt16() is Type safe conversion. But what makes these different here? Maybe it's a silly question but I'm confused. Please clarify this for me and correct me where I'm wrong.

推荐答案

数字常量 10 被视为整数,更具体地说是 Int32 。尽管您将变量键入为 object ,但隐藏在其内仍然是整数。您只能直接将值类型拆箱为相同类型或该类型的可空版本。

The numeric literal 10 is treated as an integer, and more specifically an Int32. Though you typed your variable as object, under the covers it is still the integer. You can only unbox a value type to its same type, or to a nullable version of that type, directly.

例如,这段代码:

int i = 10;
object o = i;
short j = (short)o; 

将不会执行,因为 i 不是短整数,它是整数。

Will not execute, because the original value of i is not a short, it is an integer. You have to first unbox to integer, then you can cast to short.

short j = (short)(int)o;

Convert.ToInt16 回避了该问题,并且它的实现方式是实现细节。但是,该方法具有多个重载,可以接受包括字符串在内的多种类型,因此,等效于使用直接强制转换的代码。

Convert.ToInt16 sidesteps that issue, and the way it does it is an implementation detail. However, that method has multiple overloads that accepts multiple types, including strings, so it is not the equivalent of code using a direct cast.

编辑:我注意到我在这里混用术语,因此对于C#初学者来说很清楚,名称 short Int16 可以互换使用16位整数,名称 int Int32 表示32位整数。在C#中, short int 是.NET类型 Int16 Int32

I noticed I'm mixing terms here, so just so it's clear for a novice C# reader, the names short and Int16 are interchangeable for a 16 bit integer, as are the names int and Int32 for 32 bit integers. In C#, short and int are aliases for the .NET types Int16 and Int32, respectively.

这篇关于Convert.ToInt16和(Int16)有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆