标志枚举的使用大多是在标记多重状态,比如说文件的属性:只读,可写,隐藏,系统文件等相关属性,都对应相应的标志位,如果在C#中想实现自己的标志枚举,也是可以的,下文是亲身试验的一段代码,希望对您有所帮助,也望您不吝赐教。
// 执行代码
private void Form1_Load(object sender, EventArgs e)
{
Log.i("=========================================");
StatusAttributes sa = StatusAttributes.Welcome | StatusAttributes.Login;
Log.e(sa);
Log.e(Convert.ToString((int)sa, 2));
if ((sa & StatusAttributes.Login) == StatusAttributes.Login)
Log.w("im login");
// &按位与
if ((sa & StatusAttributes.Meeting) != StatusAttributes.Meeting)
Log.w("im not in meeting");
// ^异或运算 不同则为1 相同则为0
sa = sa ^ StatusAttributes.Meeting;
Log.e(sa);
Log.e(Convert.ToString((int)sa, 2));
// ~取反
Log.e(~sa);
Log.e(Convert.ToString((int)~sa, 2));
Log.i("=========================================");
FileAttributes fa = (FileAttributes)10;
Log.e(fa);
if ((fa & FileAttributes.Administrator) == FileAttributes.Administrator)
Log.w("created by administrator");
if ((fa & FileAttributes.Hide) != FileAttributes.Hide)
Log.w("file is show");
FileAttributes fa2 = fa ^ FileAttributes.Hide;
Log.e(fa2);
if ((fa2 & FileAttributes.Readonly) != FileAttributes.Readonly)
Log.w("file2 can read and write");
}
注意:a << b 的意思为:二进制的a向左移动b位
// 枚举类型
[Flags]
public enum StatusAttributes
{
None = 0,
Welcome = 1 << 0,
Login = 1 << 1,
Meeting = 1 << 2,
Share = 1 << 4,
Join = 1 << 8,
}
[Flags]
public enum FileAttributes
{
None = 0,
System = 1,
Readonly = 2,
Hide = 4,
Administrator = 8,
}
输出结果
12-27 16:42:32.019 i =========================================
12-27 16:42:32.023 e Welcome, Login
12-27 16:42:32.024 e 11
12-27 16:42:32.024 w im login
12-27 16:42:32.024 w im not in meeting
12-27 16:42:32.024 e Welcome, Login, Meeting
12-27 16:42:32.024 e 111
12-27 16:42:32.025 e -8
12-27 16:42:32.025 e 11111111111111111111111111111000
12-27 16:42:32.025 i =========================================
12-27 16:42:32.025 e Readonly, Administrator
12-27 16:42:32.025 w created by administrator
12-27 16:42:32.025 w file is show
12-27 16:42:32.025 e Readonly, Hide, Administrator
最后列出如何位运算修改标志枚举:
StatusAttributes sa = StatusAttributes.Login | StatusAttributes.Welcome;
sa = sa | StatusAttributes.Join;//添加属性
sa = sa | StatusAttributes.Share;//添加属性
sa = (sa | StatusAttributes.Share) ^ StatusAttributes.Share;//删除属性
sa = (sa | StatusAttributes.Meeting) ^ StatusAttributes.Meeting;//删除属性