无法理解具有0x2值的Enum Flags

时间:2016-01-20 06:15:44

标签: c# enums enum-flags

我试图理解一部分代码,但到目前为止还无法理解......

[Flags]
public enum Products
{
  Pepsi = 0x1,
  Coca = 0x2,
  Miranda = 0x3,
  Dew = 0x4,
  Wine = 0x5 
} 


Products pp = (Products)12;
pp.HasFlag(Products.Dew); ==> True
pp.HasFlag(Products.Miranda); ==> False
pp.HasFlag(Products.Coca); ==> False

我想知道为什么pp.HasFlag(Products.Dew)Truepp.HasFlag(Products.Miranda)False。我认为它的工作原理是0x1 = 1,0x2 = 2,0x3 = 4,0x4 = 8,0x5 = 16.请指导我发生了什么

4 个答案:

答案 0 :(得分:4)

你误解了0x的意思。 0x5不等于16,它等于5. 0x允许你写十六进制,这样你就可以写0xA = 10。

将您的定义更改为:

public enum Products
{
    Pepsi = 1,
    Coca = 2,
    Miranda = 4,
    Dew = 8,
    Wine = 16 
} 

因此,12代表标志DewMiranda

答案 1 :(得分:1)

您的初始声明等于

[Flags]
public enum Products
{
  Pepsi = 0x1,
  Coca = 0x2,
  Miranda = Coca | Pepsi, // equals to 0x3 since 0x3 == 0x2 | 0x1
  Dew = 0x4,
  Wine = Dew | Pepsi      // equals to 0x5 since 0x5 == 0x4 | 0x1
} 

你可能想要

[Flags]
public enum Products
{
  Pepsi = 0x1,
  Coca = 0x2,
  Miranda = 0x4,
  Dew = 0x8,
  Wine = 0x10
} 

答案 2 :(得分:0)

您应该阅读this topic。 你的旗帜有点不正确。例如:

<html ng-app="Sample">
<head>
<link rel="stylesheet" href="../css/bootstrap.min.css" />
<link rel="stylesheet" href="../css/custom.css" />
<script src="../js/jquery.min.js"></script>
<script src="../js/bootstrap.min.js"></script>
<script src="../js/angular.min.js"></script>
<script src="../js/angular-animate.min.js"></script>
<script src="../js/angular-route.min.js"></script>
<script src="../js/script.js"></script>
<script src="https://code.angularjs.org/1.3.0-rc.2/angular-messages.js"></script>

</head>
<body>
    <div class="container" id="wrapper1" align="center" ng-controller="RegistrationController as registration" >
        <div>
            <img id="logoDiv" src="../images/favicon.png">
        </div>
        <div id="loginDiv">
            <h2>Sign up</h2>

            <form>
                <input type="text" class="resizedTextbox" ng-model="email" placeholder="Email" /><br> <br>
                <input type="text" class="resizedTextbox" placeholder="Password" /><br><br> 
                 <input type="text" class="resizedTextbox" placeholder="Verify Password" /><br><br> 
               <a href="#/signUp"> <button class="resizedBtn" value="SIGN UP">SignUp
                </button></a>
            </form>
        </div>
    </div>

    </body>
    </html>

逻辑上正确的标志:

Pepsi | Cola = Miranda
 0001 | 0010 = 0011

答案 3 :(得分:0)

为了理解Flags,最好将每个标志值转换为其二进制表示。所以在你的情况下我们有:

[Flags]
public enum Products
{
  Pepsi = 0x1, //--> 0001
  Coca = 0x2, //--> 0010
  Miranda = 0x3, //--> 0011
  Dew = 0x4, //--> 0100
  Wine = 0x5 // --> 0101
} 

然后当12(二进制为'1100')转换为Products枚举时,您可以清楚地看到Dew(即0100)的标志位为打开(或二进制为1)。换句话说,右边第三位的每个产品都有1个Dew。