C#中的枚举类型,原来有这么多用法

来源:互联网 发布:nginx 缓存静态文件 编辑:程序博客网 时间:2024/06/07 08:04

  枚举型的隐含类型为 int 型, 例如 int x=(int)Days.Sat ; 一点问题没有。据MSDN说枚举类型的隐含类型可以为除了char以外的任意数字类型…… [ Every enumeration type has an underlying type, which can be any integral type except char. ]

  下面这个例程演示使用长整型作为枚举的隐含类型:

  // keyword_enum2.cs

  // Using long enumerators

  using System;

  public class EnumTest

  {

  enum Range :long {Max = 2147483648L, Min = 255L};

  static void Main()

  {

  long x = (long)Range.Max;

  long y = (long)Range.Min;

  Console.WriteLine("Max = {0}", x);

  Console.WriteLine("Min = {0}", y);

  }

  }

  如果需要重新取回长整形值,也是一个转换就可以了。 long x = (long)Range.Max;

  最有意思的还是下面要说的,enum的[Flags]标记。啥也不说啦,看程序吧:

  //The following code example illustrates the use and effect of the

  //System.FlagsAttribute attribute on an enum declaration.

  // enumFlags.cs

  // Using the FlagsAttribute on enumerations.

  using System;

  [Flags]

  public enum FileAttribute

  {

  ReadOnly= 0x01,

  Hide= 0x02,

  System= 0x04,

  Archived= 0x08

  sxbjz.blog.jp

  hzbjz.blog.jp

  jnbjz.blog.jp

  dybjz.blog.jp

  hfbjz.blog.jp

  }

  class FlagTest

  {

  static void Main()

  {

  FileAttributeoptions options= FileAttribute.ReadOnly| FileAttribute.System;

  Console.WriteLine(options);

  Console.WriteLine((int)options);

  }

  }

  输出为:

  ReadOnly, System

  labjz.blog.jp

  czbjz.blog.jp

  chuz.blog.jp

  zzmz.blog.jp

  jcbjz.blog.jp

  nbbjz.blog.jp

  5

  看到了吧?呵呵。这就是常用的标志位阿~ 在C#里变得更简单易用了。

  有enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

  1> 我给定一个值1,怎样把对应的Sun以字符串的形式返回来?(常用在取数据库里的XXX_ID并转换成对应的值的时候用。——不过有点硬编码的感觉。)

  答:Convert.ChangeType( enumValue, enumType ).ToString();// enumValue=1; enumType=typeof(Days)

  2>我给定一个字符串"Sun",怎么返回enum Day.Sun?

  答: 可以直接用 Enum.Parse( enumType, string,[boolean])来解决问题. ;例如这个例子, Enum.Parse(typeof(Day), "Sun", true) 就返回Day.Sun , 第3个参数指定是否大小写敏感. 可以省略.

  3>我想知道 enum Day 中所有的字符串值. 怎么写?

  答: 这个貌似也很简单哦, foreach(string name in Enum.GetNames(typeof(Day))) Console.WriteLine(name); 还有一个Enum.GetName() ,具体用法看MSDN去吧....

0 0
原创粉丝点击