我偶然发现在枚举定义中使用了plus()运算符,我很惊讶地看到随附的测试通过了.任何人都知道这可能记录在哪里?
public enum ApprovalItemState { Enqueued = 1,Approved = 2,Denied = 4,Acknowledged = 8,ApprovalAcknowledged = ApprovalItemState.Approved + ApprovalItemState.Acknowledged,DenialAcknowledged = ApprovalItemState.Denied + ApprovalItemState.Acknowledged } [TestClass] public class ApprovalItemStateTests { [TestMethod] public void AreFlagsDeniedAndAcknowledged() { Assert.AreEqual(ApprovalItemState.DenialAcknowledged,ApprovalItemState.Denied | ApprovalItemState.Acknowledged); } [TestMethod] public void IsDenialAcknowledged() { Assert.IsTrue(Enum.IsDefined(typeof(ApprovalItemState),ApprovalItemState.Denied | ApprovalItemState.Acknowledged)); Assert.AreEqual(ApprovalItemState.Denied | ApprovalItemState.Acknowledged,(ApprovalItemState)Enum.Parse(typeof(ApprovalItemState),"DenialAcknowledged")); } [TestMethod] public void IsNotDeniedAndApproved() { Assert.IsFalse(Enum.IsDefined(typeof(ApprovalItemState),ApprovalItemState.Approved | ApprovalItemState.Denied)); } }
解决方法
14.5中的C#语言规范指出:
The following operators can be used on values of enum types: ==,!=,<,>,<=,>= (§7.10.5),binary + (§7.8.4),binary ‑ (§7.8.5),^,&,| (§7.11.2),~ (§7.7.4),++ and — (§7.6.9 and §7.7.5).
基本上,由于枚举在内部存储为Int32(这是默认值,除非您指定不同的存储类型),您可以像这样使用添加.
但是,使用|更常见而不是定义面具.此外,如果您要将此作为标志枚举使用,则通常会包含[Flags].