• 采用位或的枚举处理(示例)


        public class EnumTest
        {
            [Fact]
            public void EnumOR()
            {
                var mix = TestEnum.apple | TestEnum.orange;
                Assert.True((mix & TestEnum.apple) != 0);
                Assert.True((3 & 2) != 0);
                Assert.True((3 & (int)TestEnum.apple) != 0);
                Assert.True((mix & TestEnum.tomato) == 0);
                Assert.True((3 & (int)TestEnum.tomato) == 0);
                Assert.True(mix.HasFlag(TestEnum.orange));
    
                Assert.True(mix.ToString()== "apple, orange");
                Assert.True((int)mix == 3);
            }
    
            [Flags]
            public enum TestEnum
            {
                apple=1,
                orange=2,
                potato=4,
                tomato=8
            }
        }
    

      

    原文:https://stackoverflow.com/questions/3883384/practical-applications-of-bitwise-operations

    I use bitwise operators for security in my applications. I'll store the different levels inside of an Enum:

    [Flags]
    public enum SecurityLevel
    {
        User = 1, // 0001
        SuperUser = 2, // 0010
        QuestionAdmin = 4, // 0100
        AnswerAdmin = 8 // 1000
    }
    

    And then assign a user their levels:

    // Set User Permissions to 1010
    //
    //   0010
    // | 1000
    //   ----
    //   1010
    User.Permissions = SecurityLevel.SuperUser | SecurityLevel.AnswerAdmin;
    

    And then check the permissions in the action being performed:

    // Check if the user has the required permission group
    //
    //   1010
    // & 1000
    //   ----
    //   1000
    if( (User.Permissions & SecurityLevel.AnswerAdmin) == SecurityLevel.AnswerAdmin )
    {
        // Allowed
    }

     public class EnumTest    {        [Fact]        public void EnumOR()        {            var mix = TestEnum.apple | TestEnum.orange;            Assert.True((mix & TestEnum.apple) != 0);            Assert.True((3 & 2) != 0);            Assert.True((3 & (int)TestEnum.apple) != 0);            Assert.True((mix & TestEnum.tomato) == 0);            Assert.True((3 & (int)TestEnum.tomato) == 0);            Assert.True(mix.HasFlag(TestEnum.orange));
                Assert.True(mix.ToString()== "apple, orange");            Assert.True((int)mix == 3);        }
            [Flags]        public enum TestEnum        {            apple=1,            orange=2,            potato=4,            tomato=8        }    }

  • 相关阅读:
    开关门(结构体)
    洗牌问题(找规律)
    七夕节(hd1215)干嘛今天做这题T_T
    三角形(hd1249)
    寒冰王座(hd1248)
    钱币兑换问题(hd1284)
    计算机模拟(hd1283)
    回文数猜想(hd1282)
    贪吃蛇代码
    变形课hd1181(DFS)
  • 原文地址:https://www.cnblogs.com/panpanwelcome/p/13936651.html
Copyright © 2020-2023  润新知