加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 检查枚举标志的最佳做法[已关闭]

发布时间:2020-12-15 06:49:43 所属栏目:百科 来源:网络整理
导读:我注意到这两个模式用于检查枚举标志: [Flags]public enum PurchaseType{ None = 0,SalePrice = 2,RegularPrice = 4,Clearance = 8,CreditCard = 16}public void Test(){ PurchaseType type = PurchaseType.Clearance; type |= PurchaseType.CreditCard; //
我注意到这两个模式用于检查枚举标志:
[Flags]
public enum PurchaseType
{
    None = 0,SalePrice = 2,RegularPrice = 4,Clearance = 8,CreditCard = 16
}

public void Test()
{
    PurchaseType type = PurchaseType.Clearance;
    type |= PurchaseType.CreditCard;

    // Practice 1
    if ((type & PurchaseType.Clearance) == PurchaseType.Clearance)
    {
        // Clearance item handling
    }

    // Practice 2
    if ((type & PurchaseType.CreditCard) != 0)
    {
        // Credit card item handling   
    }
}

在检查枚举标志的两种方式中,哪一种更好的是性能,可读性,代码健康以及我应该做的其他任何考虑?

谢谢,
穆罕默德

解决方法

.Net 4引入了一种确定在当前实例中是否设置了一个或多个位字段的 HasFlag方法,这是迄今为止最佳实践:
type.HasFlag(PurchaseType.CreditCard);  // true

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读