VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • c#中装箱和拆箱的简单描述

制作者:剑锋冷月 单位:无忧统计网,www.51stat.net
 

  C#语言还是比较常见的东西,这里我们主要介绍C#装箱和拆箱,包括介绍调用该 TestAlias() 函数等方面。

  C#装箱和拆箱还是别名

  许多 C#.NET 的书上都有介绍 int -> Int32 是一个装箱的过程,反之则是拆箱的过程。许多其它变量类型也是如此,如:short <-> Int16,long <-> Int64 等。对于一般的程序员来说,大可不必去了解这一过程,因为这些C#装箱和拆箱的动作都是可以自动完成的,不需要写代码进行干预。但是我们需要记住这些类型之间的关系,所以,我们使用“别名”来记忆它们之间的关系。

  C# 是全面向对象的语言,比 Java 的面向对象都还彻底——它把简单数据类型通过默认的装箱动作封装成了类。Int32、Int16、Int64 等就是相应的类名,而那些我们熟悉的、简单易记的名称,如 int、short、long 等,我们就可以把它称作是 Int32、Int16、Int64 等类型的别名。

  那么除了这三种类型之外,还有哪些类有“别名”呢?常用的有如下一些:

  ◆bool -> System.Boolean (布尔型,其值为 true 或者 false)

  ◆char -> System.Char (字符型,占有两个字节,表示 1 个 Unicode 字符)

  ◆byte -> System.Byte (字节型,占 1 字节,表示 8 位正整数,范围 0 ~ 255)

  ◆sbyte -> System.SByte (带符号字节型,占 1 字节,表示 8 位整数,范围 -128 ~ 127)

  ◆ushort -> System.UInt16 (无符号短整型,占 2 字节,表示 16 位正整数,范围 0 ~ 65,535)

  ◆uint -> System.UInt32 (无符号整型,占 4 字节,表示 32 位正整数,范围 0 ~ 4,294,967,295)

  ◆ulong -> System.UInt64 (无符号长整型,占 8 字节,表示 64 位正整数,范围 0 ~ 大约 10 的 20 次方)

  ◆short -> System.Int16 (短整型,占 2 字节,表示 16 位整数,范围 -32,768 ~ 32,767)

  ◆int -> System.Int32 (整型,占 4 字节,表示 32 位整数,范围 -2,147,483,648 到 2,147,483,647)

  ◆long -> System.Int64 (长整型,占 8 字节,表示 64 位整数,范围大约 -(10 的 19) 次方 到 10 的 19 次方)

  ◆float -> System.Single (单精度浮点型,占 4 个字节)

  ◆double -> System.Double (双精度浮点型,占 8 个字节)

  我们可以用下列代码做一个实验:

private void TestAlias() {  
// this.textBox1 是一个文本框,类型为 System.Windows.Forms.TextBox  
// 设计中已经将其 Multiline 属性设置为 true  
byte a = 1; char b = 'a'; short c = 1;  
int d = 2; long e = 3; uint f = 4; bool g = true;  
this.textBox1.Text = "";  
this.textBox1.AppendText("byte -
>
 " + a.GetType().FullName + "\n");  
this.textBox1.AppendText("char -
>
 " + b.GetType().FullName + "\n");  
this.textBox1.AppendText("short -
>
 " + c.GetType().FullName + "\n");  
this.textBox1.AppendText("int -
>
 " + d.GetType().FullName + "\n");  
this.textBox1.AppendText("long -
>
 " + e.GetType().FullName + "\n");  
this.textBox1.AppendText("uint -
>
 " + f.GetType().FullName + "\n");  
this.textBox1.AppendText("bool -
>
 " + g.GetType().FullName + "\n");  
} 

  在窗体中新建一个按钮,并在它的单击事件中调用该 TestAlias() 函数,我们将看到运行结果如下:

byte -
>
 System.Byte  
char -
>
 System.Char  
short -
>
 System.Int16  
int -
>
 System.Int32  
long -
>
 System.Int64  
uint -
>
 System.UInt32  
bool -
>
 System.Boolean 

  这足以说明各别名对应的类!


相关教程