zoukankan      html  css  js  c++  java
  • 采用位或的枚举处理(示例)

        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        }    }

  • 相关阅读:
    蔚来汽车笔试题---软件测试
    python 装饰器
    adb
    新手安装禅道至本地
    各种验证码应该如何给值
    int col = Integer.parseInt(args[0]);的用法
    找不到jsp文件:ctrl+shift+R
    通过服务器获取验证码
    Sublime Text 2: [Decode error
    爬虫爬取新闻(二)
  • 原文地址:https://www.cnblogs.com/panpanwelcome/p/13936651.html
Copyright © 2011-2022 走看看