Go homepage(回首页) Upload pictures (上传图片) Write articles (发文字帖)
The author:(作者)qqpublished in(发表于) 2014/7/11 9:21:50 C#教程:C#数据类型之值的类型
值类型在C#中数据类型为Common Type System(CTS),包括值类型和引用类型。值类型直接存储值,而引用类型存储的是对值的引用。将一个值类型变量赋值给另一个值类型含的值,这与引用类型变量的赋值不同,引用类型变量的赋值时只复制对对象的引用,而不复制对象本身。本教程来自http://www.isstudy.com与引用类型不同,从值类型不可能派生出新的类型。但与引用类型相同,其结构也可以实现接口。值类型不包含null值,但引用类型可以。C#中的值类型如表1所示。表1 C#值类型表值类型包括布尔型、字符型和枚举类型。布尔型的值域为True/False。字符型的值域表示一个16位的Unicode字符。枚举(enum)是值类型的一种特殊形式,它从System.Enum继承而来,并为基础类型的值提供替代名称。枚举类型有名称、基础类型和一组字段。基础类型必须是一个内置的有符号(或无符号)整数类型(如Byte、Int32或UInt64)。字段是静态文本字段,其中的每一个字段都表示常数。同一个值可以分配给多个字段。出现这种情况时,必须将其中某个值标记为主要枚举值,以便进行反射和字符串转换。用户可以将基础类型的值分配给枚举,反之亦然(运行库不要求强制转换);也可创建枚举的实例,并调用System.Enum的方法以及对枚举基础类型定义的任何方法。对于枚举还有以下附加限制。枚举不能定义自己的方法。枚举不能实现接口。枚举不能定义属性或事件。Flags属性表示一种特殊的枚举,称为位域。运行库本身不区分传统枚举与位域,但编程语言要区分二者。区分二者时,可以对位域(而不是枚举)使用位操作符以产生未命名的值。枚举一般用于列出惟一的元素,如一周的各天、国家、地区和名称等。位域一般用于列出可能联合发生的质量或数量,如红色、大和快。示例域和传统枚举的使用下面的示例代码演示了如何使用位域和传统枚举。using System;using System.Collections.Generic;using System.Text;//添加命名空间using System.Collections;namespace EnumTest{public enum SomeRootVegetables{[Flags]public enum Seasons{无 = 0,夏天 = 1,秋天 = 2,冬天 = 4,春天 = 8,所有季节 = 夏天 | 秋天 | 冬天 | 春天,}class Program{static void Main(string[] args){Hashtable AvailableIn = new Hashtable();AvailableIn[SomeRootVegetables.山葵] = Seasons.所有季节;AvailableIn[SomeRootVegetables.萝卜] = Seasons.春天;AvailableIn[SomeRootVegetables.甘蓝] = Seasons.春天 |Seasons.秋天;// 声明一个Seasons类型的数组,使用枚举值Seasons[] seasons = new Seasons[] { Seasons.冬天, Seasons.春天,Seasons.夏天, Seasons.秋天 };// 将结果显示出来for (int i = 0; i < seasons.Length; i++){Console.WriteLine("rn下面的蔬菜被收获在 " + seasons[i].ToString("G") + ":");foreach (DictionaryEntry e in AvailableIn){if (((Seasons)e.Value & seasons[i]) > 0)Console.WriteLine("t" +((SomeRootVegetables)e.Key).ToString("G"));}}Console.ReadLine();}}}按键运行程序,运行结果如图1所示。图1 运行结果本教程来自 http://www.isstudy.com完整程序代码如下:★★★★★主程序文件完整程序代码★★★★★using System;using System.Collections.Generic;using System.Text;using System.Collections;namespace _2_01{public enum SomeRootVegetables{山葵,萝卜,甘蓝}[Flags]public enum Seasons{无 = 0,夏天 = 1,秋天 = 2,冬天 = 4,春天 = 8,所有季节 = 夏天 | 秋天 | 冬天 | 春天,}class Program{static void Main(string[] args){Hashtable AvailableIn = new Hashtable();AvailableIn[SomeRootVegetables.山葵] = Seasons.所有季节;AvailableIn[SomeRootVegetables.萝卜] = Seasons.春天;AvailableIn[SomeRootVegetables.甘蓝] = Seasons.春天 |Seasons.秋天;// 声明一个Seasons类型的数组,使用枚举值Seasons[] seasons = new Seasons[] { Seasons.冬天, Seasons.春天,Seasons.夏天, Seasons.秋天 };// 将结果显示出来for (int i = 0; i < seasons.Length; i++){Console.WriteLine("rn下面的蔬菜被收获在 " + seasons[i].ToString("G") + ":");foreach (DictionaryEntry e in AvailableIn){if (((Seasons)e.Value & seasons[i]) > 0)Console.WriteLine("t" +((SomeRootVegetables)e.Key).ToString("G"));}}Console.ReadLine();}}}
赞