开发者

How to use Flags attribute?

I have some items in database. Each of'em can have many tags, like Browsable, or IsInMenu and so on. A friend of mine suggested to use enums with Flags attribute to create an extensible solution. So, I created a field in DB which takes an integer value, then I created this enum:

 [Flags]
 public enum ItemTags { Browsable = 2, IsInMenu = 4}

Now I'd like to be able to semantically get the list of some items this way:

 public List<Item> GetItems(ItemTags tags)
 {
     /* 
     Code to get data from DB, something like, 
     return repository.GetList(tags);
     */
 }    

and in UI, I'd like to call:

 List<Item> items =  GetItems(ItemTags.Browsable | ItemTags.IsInMneu);

But I don't get the desired result. Am I going the right way? By desired result, I mean this: Values stored in database could be one of the 0, 2, 4, 6 values now. 0 means that the item is not in Menu and also not Browsable. 2 Means that item is Browable, but not in Menu. 4 means item is in Menu, but not Browsable. 6 means item is both Browsable and IsInMenu. N开发者_JS百科ow when I call GetItems function, I don't get all the items which are browsable, in menu, or both browsable and in menu.


You need to use FlagsAttribute, see this MSDN article, and this usage example, and most importantly this stack overflow answer.


use the FlagsAttribute Class

Indicates that an enumeration can be treated as a bit field; that is, a set of flags.

[Flags] 
public enum ItemTags 
{ 
  Default =0,
  Browsable = 2, 
  IsInMenu = 4,
  All = 6 // Browsable / IsInMenu
}

More here

note about enums:

an Enum by default has an int under­neath, and as do all inte­gers in C# an enum has a default value of 0 when first cre­ated. So if 0 is not mapped to an enu­mer­a­tion con­stant then your enum will be instan­ti­ated with an invalid valid


You are missing the Flags attribute...

Your enum should be declared like this:

[Flags]
public enum ItemTags { Browsable = 2, IsInMenu = 4}

EDIT:
After your update, it looks fine. You should be more precise in what you mean with:

But I don't get the desired result.

The code you showed us looks fine. So either there is a problem elsewhere or the code you really use in your application and the code you showed us here are different.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜