【发布时间】:2011-05-24 04:21:09
【问题描述】:
我以前没有真正使用过按位枚举,我只是想确保我的测试是正确的。我最感兴趣的是测试 None 和 All 的值。我们从 Web 服务接收数据,该服务利用此枚举对某些数据进行分类。鉴于此,我假设 None 或 All 都不会与任何其他值结合使用。
给定以下按位枚举定义;
[System.FlagsAttribute()]
public enum TrainingComponentTypes : int
{
None = 0,
AccreditedCourse = 1,
Qualification = 2,
Unit = 4,
SkillSet = 8,
UnitContextualisation = 16,
TrainingPackage = 32,
AccreditedCourseModule = 64,
All = 127,
}
我在this MSDN site 上阅读了以下关于 FlagAttributes 的引述;
使用 None 作为标志的名称 枚举常量,其值为 零。您不能使用无 按位与枚举常量 测试标志的操作,因为 结果始终为零。然而, 你可以执行一个逻辑,而不是 按位比较 数值和 None 枚举 常量来确定是否有任何位 在数值中设置。
在这种情况下,逻辑比较是否指的是枚举的正常相等测试? 例如;
TrainingComponentTypes tct = TrainingComponentTypes.None;
if (tct == TrainingComponentTypes.None)
{ ... }
对于按位比较,我正在执行以下操作;
TrainingComponentTypes tct = TrainingComponentTypes.AccreditedCourse | TrainingComponentTypes.Qualification | TrainingComponentTypes.TrainingPackage;
Assert.IsTrue((tct & TrainingComponentTypes.AccreditedCourse) == TrainingComponentTypes.AccreditedCourse, "Expected AccreditedCourse as part the enum");
Assert.IsFalse((tct & TrainingComponentTypes.SkillSet) == TrainingComponentTypes.SkillSet, "Found unexpected SkillSet as part the enum");
最后,在对所有人进行测试时,我尝试了逻辑比较和按位比较,它们都返回相同的结果。我应该在这里使用另一个吗?例如;
TrainingComponentTypes tct = TrainingComponentTypes.All;
Assert.IsTrue((tct & TrainingComponentTypes.All) == TrainingComponentTypes.All, "Expected All as part the enum");
Assert.IsTrue((tct) == TrainingComponentTypes.All, "Expected All as part the enum");
// The follow also pass the assertion for a value of All
Assert.IsTrue((tct & TrainingComponentTypes.Qualification) == TrainingComponentTypes.Qualification, "Expected Qualification as part the enum");
Assert.IsTrue((tct & TrainingComponentTypes.TrainingPackage) == TrainingComponentTypes.TrainingPackage, "Expected TrainingPackage as part the enum");
总之,我想了解以下有关位枚举的信息;
- 是我对逻辑的理解 给出我的例子比较正确 多于?
- 是我的表现方式 按位比较正确吗?
- 处理“全部”的正确方法是什么 值(按位或逻辑)。我不确定我们是否会收到 All 与其他 TrainingComponentTypes 组合的值。我不明白为什么我们会,但是,你永远不知道吗?
- 我假设那个开关是对的吗 声明基本上不应该 用于按位枚举(无 似乎是一种特殊情况,并且 需要逻辑比较)?
谢谢, 克里斯
【问题讨论】:
标签: c# enums comparison bit-manipulation bit