第十三章 枚举类型与位标记[《.net框架程序设计》读书笔记]

** 第十三章 ** ** ** ** 枚举类型与位标记 ** ** **

** 一、 ** ** 枚举类型 **

1、 使用枚举类型的理由:

l 枚举类型是得程序更容易编写、阅读、维护,在代码中使用符号名称代替数字是程序设计的一贯主张。

l 强类型的,便于类型检验

2、 注意事项:

l 枚举类型继承自 System.Enum , System.Enum 又继承自 System.ValurType

l 枚举类型不能定义方法、属性、事件

l 枚举类型为常数而非只读字段,因此可能引入版本问题(见 第八章 的相关讨论)

l 将枚举类型与引用它的类型定义在同一层次上,可减少代码录入的工作量

3、 System.Enum 中方法的应用:

l         **public static** Type **GetUnderlyingType(** Type ****_enumType_ **);**


获取用于保存枚举类型实例值得基础类型。声明某枚举类型使用的基础类型语法如下:


enum Human : byte


{


    Male,


    Female


}


则调用上述方法Enum.GetUnderlyingType(typeof(Human));将返回System.Byte;


l         **public override string ToString();**


**   public string ToString(string)**;     //参数为格式字符串


**   public static **string **Format(** Type ****_enumType_ **,** object ****_value_ **,** string ****_format_ **);**


            //Value – 要转换的值,format – 格式字符串(G,g,X,x,D,d,F,f)


l         **public static** Array **GetValues(** Type ****_enumType_ **);** ****


 获取枚举中常数值的数组


l         **public static** **string GetName(Type _enumType_ ,object _value_ );**


在指定枚举中检索具有指定值的常数的名称


l         **public static** string **[] GetNames(** Type ****_enumType_ **);**


检索指定枚举中常数名称的数组。


l         **public static object Parse(Type, string);**


** public static object Parse(Type, string, bool);**


将一个或多个枚举常数的名称或数字值的字符串表示转换成等效的枚举对象


l         **public static** **bool IsDefined(Type _enumType_ ,object _value_ );**


返回指定枚举中是否存在具有指定值的常数的指示,value为常数的值或名称


l         系列 **ToObject** 方法


返回设置为指定值的、指定枚举类型的实例

** 二、 ** ** 位标记 **

l 使用 System.FlagsAttributes 定制特性,使得 ToString 或 Format 方法可以查找枚举数值中的每个匹配符号,将它们连接为一个字符串,并用逗号分开; Parse 方法可用该特性拆分字符串并得到复合的枚举类型

l 使用格式字符串 F 或 f 也有同样的效果

下面的示例说明上述情况

using System;

[Flags] // 定制特性

public enum Human : byte // 定制基本类型

{

Male = 0x01,

Female = 0x10

}

public class EnumTest

{

public static void Main ()

{

Human human = Human.Male | Human.Female; // 人妖?

Console.WriteLine(human.ToString()); // 使用 Flags 定制特性的情况

//Console.WriteLine(human.ToString("F")); // 没有使用 Flags 定制特性的情况

Console.WriteLine(Enum.Format(typeof(Human), human, "G"));// 使用 Flags 定制特性的情况

//Console.WriteLine(Enum.Format(typeof(Human), human, "F"));// 没有使用 Flags 定制特性的情况

human = (Human)Enum.Parse(typeof(Human), "17");

Console.WriteLine(human.ToString()); // 使用 Flags 定制特性的情况

//Console.WriteLine(human.ToString("F")); // 没有使用 Flags 定制特性的情况

}

}

/* 运行结果

Male, Female

Male, Female

Male, Female

*/

注: 上述程序中的注释为不使用 Flags 特性时的语法

Published At
Categories with Web编程
Tagged with
comments powered by Disqus