C# 使用“位运算”进行多状态查询

    class Program
    {
        public enum ProjectStatus
        {
            Received = 256,
            Checked = 128,
            Exam = 64,
            Null = 32,
            ReChecked = 16,
            MasterChecked = 8,
            ReportChecked = 4,
            ReportPrinted = 2,
            Finished = 1
        }

        static void Main(string[] args)
        {
            var DBStatus = Convert.ToInt32("111000000", 2);
            const int QueryStatus = (int)(ProjectStatus.ReportChecked | ProjectStatus.ReportPrinted | ProjectStatus.Finished);
            Console.WriteLine(DBStatus & QueryStatus);
            Console.Read();
        }
}


我们在设计系统的时候,经常要用到状态标志,比如文章状态“审核、未审核”,比如员工状态“在职、离职、休假”

按照旧的设计方法,使用字符来标识,查询的时候如果使用Or进行连接,在拼接语句的时候会比较麻烦。

使用位运算的方法,我们可以将状态转换为数字存储。

查询的时候,只需要连接状态,转为数字进行对比查询。

原文地址:https://www.cnblogs.com/blackice/p/2665172.html