首页 > 开发 > .Net > 正文

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

2020-02-03 15:57:02
字体:
来源:转载
供稿:网友
  • 网站运营seo文章大全
  • 提供全面的站长运营经验及seo技术!
  • 第十三章 枚举类型与位标记

    一、 枚举类型

    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特性时的语法
    发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表