C# · 1月 30, 2022

c# – 枚举定义中的加号运算符

我偶然发现在枚举定义中使用了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].