码迷,mamicode.com
首页 > 编程语言 > 详细

C# - How to Initialize Flags Enumerations

时间:2015-03-31 20:12:19      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:c#   flags enumerations   



The most common way to initialize flags is to use hexadecimal literals.  This is how Microsoft and most C# developers do it:

[Flags]
public enum DaysOfTheWeek
{
	None = 0,
	Sunday = 0x01,
	Monday = 0x02,
	Tuesday = 0x04,
	Wednesday = 0x08,
	Thursday = 0x10,
	Friday = 0x20,
	Saturday = 0x40,
}

An even better method might be to use binary literals such as 0b0001, 0b0010, 0b0100, 0b1000, etc., but C# does not provide binary literals.  However, you can simulate a binary literal with the bit shift operator.  This method has the advantage that the numbers visually increase by 1, so it’s very easy to spot errors and see which bit is set for each flag.  Note that this method does not affect program performance because the flag values are calculated at compile time.

[Flags]
public enum DaysOfTheWeek
{
	None = 0,
	Sunday = 1 << 0,
	Monday = 1 << 1,
	Tuesday = 1 << 2,
	Wednesday = 1 << 3,
	Thursday = 1 << 4,
	Friday = 1 << 5,
	Saturday = 1 << 6,
}

C# - How to Initialize Flags Enumerations

标签:c#   flags enumerations   

原文地址:http://blog.csdn.net/troubleshooter/article/details/44782963

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!