Chinaunix首页 | 论坛 | 博客
  • 博客访问: 41960
  • 博文数量: 22
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 344
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-19 11:34
文章分类
文章存档

2014年(22)

我的朋友

分类: Android平台

2014-04-29 15:04:35




枚举位标志
StatusEffect枚举,如下:
[System.Flags]
public enum StatusEffect
{
    None    = 1,
    Poison    = 2,
    Slow    = 4,
    Mute    = 8
}
通过如此,我们告知编译器将此枚举看做是位标记,表示每个不同的枚举值代表一个不同的位。这意味着我们必须通过给它们用2的幂来赋值,以此告知每个枚举值。另一种就是通过获取两个值的幂,然后通过移位来实现:

[System.Flags]
public enum StatusEffect
{
    None   = 1 << 0, // 1
    Poison = 1 << 1, // 2
    Slow   = 1 << 2, // 4
    Mute   = 1 << 3  // 8
}
现在可以通过平常的位操作来控制这些枚举域了。如果你对位操作不熟悉,我会简单讲解下如何使用。
枚举标志和位操作符
现在我们的枚举值是通过System.Flags标记的,我们可以像之前一样,如下来做:
1
2
//Character is poisoned!
status = StatusEffect.Poison;
但如果玩家中毒或者行动缓慢怎么办?我们可以使用或|操作符来将多个状态值合并一起:

//Now we are poisoned *and* slowed!
status = StatusEffect.Poison | StatusEffect.Slow;
 
//We could also do this:
//First we are poisoned, like so
status = StatusEffect.Poison;
 
//Then we become *also* slowed later
status |= StatusEffect.Slow;
如果我们想移除一个状态效果,我们可以使用&操作符和取反~。

//First, we are poisoned and muted
status = StatusEffect.Poison | StatusEffect.Mute;
 
//But now we want to remove just the poison, and leave him mute!
status &= ~StatusEffect.Poison;
最后如果我们检测发现如果一个玩家在if语句中,我们可以使用&操作符来查看一个特定的位值:

//Let's check if we are poisoned:
if ((status & StatusEffect.Poison) == StatusEffect.Poison)
{
    //Yep, definitely poisoned!
}


阅读(1561) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~