• C# 枚举用法总结


    Enumeration的默认值是从0开始的int如下:
    enum Direction
    {
       UP,
       RIGHT
       DOWN,
       LEFT,
    };
    此时UP=0, DOWN=1...依此类推

    改变默认值:
    enum Direction
    {
       UP=1,
       RIGHT=2,
       DOWN=3,
       LEFT=4,
    };

    改变类型(只能改变成:byte, sbyte, short, ushort, int, uint, long, ulong):
    enum Direction : long
    {
        UP = 1111111111,
        DOWN = 1111111112,
        LEFT = 1111111113,
        RIGHT = 1111111114
    };

    访问Enumeration变量的值
    赋值前先cast:
    long direct = (long)Direction.UP;

    Enumeration变量的文字描述
    如果想要Enumeration返回一点有意义的string,从而用户能知道分别代表什么, 则按如下定义:
    using System.ComponentModel;
    enum Direction
    {
        [Description("this means facing to UP (Negtive Y)")]
        UP = 1,
        [Description("this means facing to RIGHT (Positive X)")]
        RIGHT = 2,
        [Description("this means facing to DOWN (Positive Y)")]
        DOWN = 3,
        [Description("this means facing to LEFT (Negtive X)")]
        LEFT = 4
    };

    使用如下方法来获得文字描述:
    using System.Reflection;
    using System.ComponentModel;
    public static String GetEnumDesc(Enum e)
    {
        FieldInfo EnumInfo = e.GetType().GetField(e.ToString());
        DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[]) EnumInfo.
            GetCustomAttributes (typeof(DescriptionAttribute), false);
        if (EnumAttributes.Length > 0)
        {
            return EnumAttributes[0].Description;
        }
        return e.ToString();
    }

    或者可以自己定义Discription Attributes
    enum Direction
    {
        [EnumDescription("Rover is facing to UP (Negtive Y)")]
        UP = 1,
        [EnumDescription("Rover is facing to DOWN (Positive Y)")]
        DOWN = 2,
        [EnumDescription("Rover is facing to RIGHT (Positive X)")]
        RIGHT = 3,
        [EnumDescription("Rover is facing to LEFT (Negtive X)")]
        LEFT = 4
    };

    AttributeUsage(AttributeTargets.Field)]
    public class EnumDescriptionAttribute : Attribute
    {
        private string _text = "";
        public string Text
        {
            get { return this._text; }
        }
        public EnumDescriptionAttribute(string text)
        {
            _text = text;
        }
    }

  • 相关阅读:
    四种方案解决ScrollView嵌套ListView问题
    [Android Bug] ListView中Header, Footer无法隐藏(gone)的问题
    Mysql介绍,与将脚本导入新数据库
    000 SpringBoot属性配置
    navicat的安装
    gradle
    004 Numpy
    003 Scipy库简介
    Mysql安装(绿色版安装)
    010 secondary namenode(同步元数据和日志)
  • 原文地址:https://www.cnblogs.com/xyqCreator/p/2435898.html
Copyright © 2020-2023  润新知