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

前端之家收集整理的这篇文章主要介绍了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].

猜你在找的C#相关文章