操纵不同二进制位代表不同意义的枚举代码示例

很多程序, 尤其是权限相关的代码, 其表示逻辑会用到让不同的二进制位代表不同意义的枚举类型.

 

对这类枚举类型的操纵和验证的代码是经常要用到的. 于是整理了一个例子列在下面. 代码是反汇编别人的工具得来的, 并非原创.

using System;
using System.Data;
using System.Text;

namespace TestApplication
{
    class Program
    {
        enum PermMask : ulong
        {
            Empty = 0L,
            Open = 0x1L, 
            Add = 0x2L,
            Edit = 0x4L,
            Delete = 0x8L, 
            Approve = 0x10L, 
            Manage = 0x20L, 
            Apply = 0x40L,
            FullMask = 0xffL
        };

        static void Main(string[] args)
        {
            Type ptype = typeof(PermMask);
            ulong uPerm = 0x13;
            Enum ePerm = (Enum)Enum.ToObject(ptype, uPerm);
            Console.WriteLine("Test value is " + uPerm.ToString() + "\n");

            Array vals = Enum.GetValues(ptype);
            int iMaxLen = 0;
            foreach (ulong val in vals)
            {
                Enum ePerm2 = (Enum)Enum.ToObject(ptype, val);
                iMaxLen = Math.Max(iMaxLen, ePerm2.ToString().Length);
            }

            StringBuilder sb = new StringBuilder();
            foreach (ulong val in vals)
            {
                sb.AppendFormat("{0," + iMaxLen + "}", 
                    ((Enum)Enum.ToObject(ptype, val)).ToString());
                sb.Append("   ");
                sb.Append(val.ToString("X16"));
                sb.Append("   ");

                if ((val & uPerm) == val)
                {
                    sb.Append(" Yes");
                }
                else
                {
                    sb.Append(" No");
                }
                sb.AppendLine();
            }

            Console.WriteLine(sb.ToString());
        }
    }
}

 

输出结果:

5-30-2010 9-48-53 PM

 

参考资料:

StringBuilder.AppendFormat Method (String, Object)

http://msdn.microsoft.com/en-US/library/hdekwk0b.aspx

posted on 2010-05-30 21:50  中道学友  阅读(588)  评论(0编辑  收藏  举报

导航

技术追求准确,态度积极向上