枚举定义中的波浪号(〜)是什么?

枚举定义中的波浪号(〜)是什么?

我一直感到很惊讶,即使在这段时间里一直使用C#之后,我仍然设法找到了我不知道的东西...


我已经尝试过在互联网上搜索此内容,但是在搜索中使用“〜”对我来说效果不佳,我也没有在MSDN上找到任何内容(并不是说它不存在)


我最近看到了这段代码,波浪号(〜)是什么意思?


/// <summary>

/// Enumerates the ways a customer may purchase goods.

/// </summary>

[Flags]

public enum PurchaseMethod

{   

    All = ~0,

    None =  0,

    Cash =  1,

    Check =  2,

    CreditCard =  4

}

看到它令我有些惊讶,所以我尝试对其进行编译,并且它起作用了……但是我仍然不知道它的含义/作用。有帮助吗?


扬帆大鱼
浏览 425回答 4
4回答

慕桂英4014372

我认为:[Flags]public enum PurchaseMethod{&nbsp; &nbsp; None = 0,&nbsp; &nbsp; Cash = 1,&nbsp; &nbsp; Check = 2,&nbsp; &nbsp; CreditCard = 4,&nbsp; &nbsp; All = Cash | Check | CreditCard&nbsp;}会更加清楚。

江户川乱折腾

public enum PurchaseMethod{&nbsp; &nbsp;&nbsp; &nbsp; All = ~0, // all bits of All are 1. the ~ operator just inverts bits&nbsp; &nbsp; None =&nbsp; 0,&nbsp; &nbsp; Cash =&nbsp; 1,&nbsp; &nbsp; Check =&nbsp; 2,&nbsp; &nbsp; CreditCard =&nbsp; 4}由于C#中有两个补码~0 == -1,因此二进制表示中所有位均为1的数字。

MMTTMM

它比All = Cash | Check | CreditCard解决方案,因为如果以后添加另一种方法,请说:PayPal = 8 ,您将已经使用tilde-All完成了所有操作,但必须更改其他所有行。因此,以后不太容易出错。
打开App,查看更多内容
随时随地看视频慕课网APP