用[Flags]属性定义C#枚举的多种方法? [英] Multiple ways to define C# Enums with [Flags] attribute?

查看:190
本文介绍了用[Flags]属性定义C#枚举的多种方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白了枚举在C#中的工作原理,我得到了Flags属性带来的表。



我看到这个问题,here 。哪个建议的第一个风味,但不提供任何理由/理由。



这两种方式有什么区别,是一个更好的比其他?使用第一个synax而不是第二个的优点是什么?我一直使用第二种风格定义Flags类型枚举...这一次我一直在做错?

  [Serializable] 
[Flags]
public enum SiteRoles
{
User = 1< 0,
Admin = 1<< 1,
Helpdesk = 1<< 2
}


$不一样b $ b

  [Serializable] 
[Flags]
public enum SiteRoles
{
User = 1,
Admin = 2,
帮助台= 4
}


解决方案>

第一个的主要优点是,您不需要为每个标志计算正确的值,因为编译器将为您执行。除此之外,他们是一样的。


I understand how Enums work in C#, and I get what the Flags attribute brings to the table.

I saw this question, here. Which recommends the first flavor, but doesn't provide any reason/justification for it.

Is there a difference in the way in which these two are defined, is one better than the other? What are the advantages to using the first synax as instead of the second? I've always used the second flavor when defining Flags type Enums... have I been doing it wrong all this time?

[Serializable]
[Flags]
public enum SiteRoles
{
    User = 1 << 0,
    Admin = 1 << 1,
    Helpdesk = 1 << 2
}

Is that not the same as

[Serializable]
[Flags]
public enum SiteRoles
{
    User = 1,
    Admin = 2,
    Helpdesk = 4
}

解决方案

The main advantage with the first one is that you don't need to calculate the correct values for each flag since the compiler will do it for you. Apart from that they are the same.

这篇关于用[Flags]属性定义C#枚举的多种方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆