C#: enum

C#的枚举类型跟C++差不多,一般我们将enum设为单个状态,比如enum color_t { RED, BLACK, GREEN}, 只能选择一个

而有的时候枚举可以作为位运算来进行与或运算,比如ControlStyles这个枚举,看下面一段从TabControlEx中的一段代码

1            base.SetStyle(

2                 ControlStyles.UserPaint |

3                 ControlStyles.OptimizedDoubleBuffer |

4                 ControlStyles.AllPaintingInWmPaint |

5                 ControlStyles.ResizeRedraw |

6                 ControlStyles.SupportsTransparentBackColor,

7                 true);

8             base.UpdateStyles();       
View Code

这里我自己写了一段代码来看个别位是否设置了

 1 using System;

 2 using System.Collections.Generic;

 3 using System.Linq;

 4 using System.Text;

 5 

 6 namespace test4

 7 {

 8     class Program

 9     {

10         public enum ChangedTypes

11         {

12             Created = 0x0001,

13             Deleted = 0x0002,

14             Changed = 0x0004,

15             Renamed = 0x0008,

16             Added = 0x0010

17         }

18         public class Image

19         {

20             private ChangedTypes types;

21             public ChangedTypes Types { get; set; }

22         }

23 

24         static void Main(string[] args)

25         {

26             Image image = new Image();

27             image.Types = ChangedTypes.Created | ChangedTypes.Changed | ChangedTypes.Added;

28             if ((image.Types & ChangedTypes.Created) == ChangedTypes.Created)

29             {

30                 Console.WriteLine("image has been Created");

31             }

32             else

33             {

34                 Console.WriteLine("image has not been Created");

35             }

36             if ((image.Types & (ChangedTypes.Created | ChangedTypes.Changed)) == (ChangedTypes.Created | ChangedTypes.Changed))

37             {

38                 Console.WriteLine("image has been Created and Changed");

39             }

40             else

41             {

42                 Console.WriteLine("image has not been Created or Changed");

43             }

44         }

45     }

46 }
View Code

 

你可能感兴趣的:(enum)