二十、枚举类型

发布时间:2020-09-22 01:20:02 作者:vik_xiao
来源:网络 阅读:260
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _20.枚举类型
{
    enum orientation : byte
    {
        north = 1,
        south = 2,
        east = 3,
        west = 4
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            /**
             * 枚举类型:
             * 使用enum关键字定义枚举类型。
             * 其定义语法:
             *  enum <typeName> [: <underlyingType>]
             *  {
             *      <value1>,
             *      <value2>,
             *      <value3>,
             *      ...
             *      <valueN>
             *  }
             *  
             * 定义枚举变量:
             *  <typeName> <varName>;
             *  
             * 引用枚举变量:
             *  <varName> = <typeName>.<value>;
             *  
             * 解析说明:
             * 1. 枚举使用一个基本类型来存储。
             * 2. 枚举类型可以提取每个值都存储为该基本类型的一个值,默认情况下该类型为int。
             * 3. <underlyingType>用来指定枚举值类型。
             * 4. 枚举的基本类型:byte,sbyte,short,ushort,int,uint,long,ulong。
             * 5. 在默认情况下,每个值都会根据定义的顺序(从0开始),自动赋值给对应的基本类型值。
             * 6. 使用=号运算符,指定每个枚举的实际值,可以多个枚举指定相同的值。
             * 7. 以循环方式指定枚举值会出现错误。
             *    例如:
             *    enum <typeName> : <underlyingType>
             *    {
             *      <value1> = <value2>,
             *      <value2> = <value1>,
             *    }
             * 
             */
             
            byte directionByte;
            string directionString
            ;
            orientation myDirection = orientation.north;
            Console.WriteLine("myDirection = {0}", myDirection);
            
            directionByte = (byte)myDirection;
            directionString = Convert.ToString(myDirection);
            
            Console.WriteLine("byte equivalent = {0}", directionByte);
            Console.WriteLine("string equivalent = {0}", directionString);
            Console.WriteLine("string equivalent = {0}", myDirection.ToString());
            
            // 以下方法作用:把string类型转换为枚举值。
            // (enumerationType)Enum.Parse(typeof(enumerationType), enumerationValueString);
            // enumerationValueString参数是区分大小写的。
            // typeof运算符是得到操作数的类型。
            
            string myString = "west";
            
            orientation direction = (orientation)Enum.Parse(typeof(orientation), myString);
            Console.WriteLine("direction = {0}", (byte)direction);
            
            Console.ReadKey();
        }
    }
}


推荐阅读:
  1. 利用枚举类型实现统计
  2. Java面试必看二十问题

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

编程

上一篇:Pandas删除数据的几种情况(小结)

下一篇:如何优雅的进行Spring整合MongoDB详解

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》