rainbowzc

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: :: :: 管理 ::
Emumeration 这个概念早在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:(来自:James Geurts' Blog)
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;
    }
}

posted on 2008-06-16 19:28  ct  阅读(887)  评论(0编辑  收藏  举报