位运算用例

枚举    

    public enum PermissionTypes : int
        {
            None = 0,
            浏览 = 1,
            分类管理 = 2,
            文档管理 = 4,
            权限管理 = 8,

            全部权限 = 浏览 | 分类管理 | 文档管理 | 权限管理
        }

是否包含

        public static bool Has(int source, int value)
        {
            try
            {
                return ((source & value) ==value);
            }
            catch
            {
                return false;
            }
        }

绑定枚举

 Utility.ItemListBind<Ph.PermissionTypes>(cbl);

取值 

       public static int GetValueFromCheckBox(CheckBoxList cbl)
        {
            int ret = 0;
            int count = cbl.Items.Count;
            if (count > 0)
                for (int i = 0; i < count; i++)
                {
                    if (cbl.Items[i].Selected)
                        ret = (ret | int.Parse(cbl.Items[i].Value));
                }
            return ret;
        }

公用类Utility:

    /// <summary>
    /// 指定控件初始值(位运算专用)
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="CBTarget"></param>
    /// <param name="strValue"></param>
    public static void SelectItemByValue<T>(CheckBoxList CBTarget, string strValue) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");

        if (!Sxmobi.Tools.IsInt(strValue)) return;

        int iCount = CBTarget.Items.Count;
        for (int i = 0; i < iCount; i++)
            if (Ph.Has(int.Parse(strValue),int.Parse(CBTarget.Items[i].Value)))
            {
                CBTarget.Items[i].Selected = true;
            }
    }

    public static void ItemListBind<T>(CheckBoxList CBTarget) where T : struct, IConvertible
    {
        if (!typeof(T).IsEnum) throw new ArgumentException("T must be an enumerated type");

        //绑定数据
        foreach (int myCode in Enum.GetValues(typeof(T)))
        {
            string myName = Enum.GetName(typeof(T), myCode);
            string myValue = myCode.ToString();
            ListItem myLi = new ListItem(myName, myValue);
            CBTarget.Items.Add(myLi);
        }
    }

原文地址:https://www.cnblogs.com/dashi/p/4034710.html