• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
敬YES
Now Or Never
博客园    首页       联系   管理    订阅  订阅
跟小静读CLR via C#(18)——Enum

1. Enum定义

枚举类型是经常用的一种“名称/值”的形式,例如:

public enum FeedbackStatus
     {
         New,
         Processing,
         Verify,
         Closed
     }

定义枚举类型之后我们在使用时方便了许多,不用再记着0代表什么状态,1代表什么状态。而且枚举类型时强类型的,在编译时就可以进行类型安全检查。枚举类型是值类型的,它是直接从System.Enum继承的,System.Enum又是继承自System.ValueType。但是枚举类型不可以定义方法、属性或者事件。

2. 常用方法

①Enum.GetUnderlyingType:获取枚举类型实例值的基类。

   Console.WriteLine(Enum.GetUnderlyingType(typeof(FeedbackStatus)));//结果System.Int32

②ToString() :转换为字符串形式

    FeedbackStatus status=FeedbackStatus .New ;
    Console.WriteLine(status.ToString());    //结果New
    Console.WriteLine(status.ToString("G")); //结果New
    Console.WriteLine(status.ToString("D")); //结果0

 

③GetValues:获取枚举类型中定义的所有符号以及对应的值。

FeedbackStatus[] status = (FeedbackStatus[])Enum.GetValues(typeof(FeedbackStatus));
            foreach(FeedbackStatus s in status )
            {
                Console.WriteLine("{0:D}--{0:G}", s);
            }

image

④GetNames:获取枚举类型中定义的所有符号。

string[] arr= Enum.GetNames(typeof(FeedbackStatus));
          foreach (string name in arr)
          {
              Console.WriteLine(name);
          }

image

⑤Parse, TryParse:将文本类型转换为对应的枚举类型。

FeedbackStatus status = (FeedbackStatus)Enum.Parse(typeof(FeedbackStatus), "New", false);
Enum.TryParse("aaa", false, out status);

⑥IsDefine:判断一个值对于一个枚举类型是否合法。

Console .WriteLine(Enum.IsDefined(typeof(FeedbackStatus),1));    //true
Console.WriteLine(Enum.IsDefined(typeof(FeedbackStatus), "New"));//true
Console.WriteLine(Enum.IsDefined(typeof(FeedbackStatus), "new"));//false,区分大小写
Console.WriteLine(Enum.IsDefined(typeof(FeedbackStatus), "aaa"));//false
Console .WriteLine(Enum.IsDefined(typeof(FeedbackStatus ),5));   //false

 

3. 扩展方法与枚举

上面提到过枚举中是不允许定义方法和事件的。但是我们可以通过扩展方法变相的为枚举添加方法。

public  static class EnumMethod
{
    public static void Show(this FeedbackStatus status)
    {
        string[] arr = Enum.GetNames(typeof(FeedbackStatus));
        Console.WriteLine("枚举类型列表:");
        foreach (string name in arr)
        {
            Console.WriteLine(name);
        }
    }
}

static void Main(string[] args)
      {
          FeedbackStatus status = FeedbackStatus.Processing;
          status.Show();

      }

image

 

 

你也许喜欢:跟小静读CLR via C#(00)-开篇及目录

作者:陈敬(公众号:敬YES)
出处:http://www.cnblogs.com/janes/
博客文章仅供交流学习,请勿用于商业用途。如需转载,请务必注明出处。

posted on 2012-02-06 14:39  敬YES  阅读(2806)  评论(13)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3