枚举(Enum)

作者:追风剑情 发布于:2019-11-1 15:56 分类:C#

示例一:定义枚举类型

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6.  
  7. namespace ConsoleApp2
  8. {
  9. class Program
  10. {
  11. static void Main(string[] args)
  12. {
  13. byte x = (byte)Days.Fri;
  14. Console.WriteLine("x={0}", x);
  15.  
  16. CarOptions car = CarOptions.SunRoof | CarOptions.Spoiler;
  17. //如果移除[Flags],将输出car=3
  18. Console.WriteLine("car={0}", car);
  19.  
  20. //打印枚举元素
  21. string[] names = Enum.GetNames(typeof(Days));
  22. foreach (var s in names)
  23. Console.WriteLine(s);
  24.  
  25. //判断有没定义某个枚举元素
  26. bool definedSun = Enum.IsDefined(typeof(Days), "Sun");
  27. bool definedSunX = Enum.IsDefined(typeof(Days), "SunX");
  28. Console.WriteLine("definedSun={0}, definedSunX={1}", definedSun, definedSunX);
  29.  
  30. Console.Read();
  31. }
  32. }
  33.  
  34. //定义枚举元素的类型为byte型,默认为int型
  35. //准许使用的枚举类型有 byte、sbyte、short、ushort、int、uint、long 或 ulong。
  36. //默认情况第1个元素的值为0,后面的元素值依次递增
  37. public enum Days : byte
  38. { Sat = 1, Sun, Mon, Tue, Wed, Thu, Fri }
  39.  
  40. [Flags] //使用System.FlagsAttribute特性
  41. public enum CarOptions
  42. {
  43. SunRoof = 0x01,
  44. Spoiler = 0x02,
  45. FogLights = 0x04,
  46. TintedWindows = 0x08
  47. }
  48. }

运行测试
1111.png

示例——枚举
internal enum Color : byte {
	White,
	Red,
	Green,
	Blue,
	Orange
}

//输出"System.Byte"
Console.WriteLine(Enum.GetUnderlyingType(typeof(Color)));

C#编译器将枚举类型视为基元类型。所以可以用许多熟悉的操作符(==,!=,<,><=,>=,+,-,^,&,|,~,++,--)来操作枚举类型的实例。所有这些操作符实际作用于每个枚举类型实例内部的 value_ 实例字段。此外,C#编译器允许将枚举类型的实例显式转型为不同的枚举类型。也可显示将枚举类型实例转型为数值类型。

示例——枚举
internal enum Color : byte {
	White,
	Red,
	Green,
	Blue,
	Orange
}

Color c = Color.Blue;
Console.WriteLine(c);		    // "Blue" (常规格式)
Console.WriteLine(c.ToString());    // "Blue" (常规格式)
Console.WriteLine(c.ToString("G")); // "Blue" (常规格式)
Console.WriteLine(c.ToString("D")); // "3" (十进制格式)
Console.WriteLine(c.ToString("X")); // "03" (十六进制格式)
//以下代码显示"Blue"
Console.WriteLine(Enum.Format(typeof(Color), 3, "G"));

示例——枚举
Color[] colors = (Color[]) Enum.GetValues(typeof(Color));
foreach (Color c in colors) {
	Console.WriteLine("{0,5:D}\t{0:G}", c);
}

public static TEnum[] GetEnumValues<TEnum>() where TEnum : struct {
	return (TEnum[])Enum.GetValues(typeof(TEnum));
}

示例——位标志
[Flags]
internal enum Actions {
	None = 0,
	Read = 0x001,
	Write = 0x0002,
	ReadWrite = Actions.Read | Actions.Write,
	Delete = 0x0004,
	Query = 0x0008,
	Sync = 0x0010
}

Actions actions = Actions.Read | Actions.Delete;
//输出"Read, Delete"
Console.WriteLine(actions.ToString());
//如果未使用[Flags]
Console.WriteLine(actions.ToString("F"));

给枚举增加扩展方法

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号