C#的值存储类别 - 位掩码 [英] C# Storing categories in a value - Bitmasks

查看:183
本文介绍了C#的值存储类别 - 位掩码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作有某些类别的应用程序。这样做的目的是存储的类别中的一个值。

首先,我选用将它们存储在一个int。

类:0,1,2,3 ...

然后我做了位掩码操作发现选择的类别。

但问题是,我不能存储更多的31类被这个中断。

I am working on an application that have some categories. The aim is to store the categories in a value.
First, I choosed to store them in an int.
Categories : 0, 1, 2, 3...
Then I do a bitmask operation to find which category was selected.
But the problem is that I can't store more that 31 categories is this int.

有没有什么办法让这样的系统?我不想去扔了无限数量的类别,但也许过64

目标语言是C#,但没有其他解决办法可能是罚款。

Is there any way to make such system ? I don't want to go threw the unlimited number of categories but maybe over 64.
The target language is C# but any other solution could be fine.

非常感谢!

推荐答案

考虑使用的 System.Collections.BitArray ,该位是一个任意长度的数组。你可以做交集(AND),工会(或),补(NOT)。

Consider using System.Collections.BitArray, which is an arbitrary-length array of bits. You can do intersections (AND), unions (OR), and complements (NOT).

您现在可以哈弗超过32类用整数键入:

You can now haver more than 32 categories keyed by integers:

public static class Categories
{
   public const int Category1 = 1;
   public const int Category2 = 2;
    //...
   public const int Category3123 = 3123;
   public const int Max = 5000;
}

BitArray myBitset = new BitArray((int)Categories.Max);
myBitSet.Set(Categories.Category1);
myBitSet.Set(Categories.Category4);

我用整数而不是枚举,以避免全部采用BitArray时所必需的强制类型转换为INT,但很明显,你可以在同类别的交易类封装了这些。

I used ints rather than enums to avoid all the casts to int that are necessary when using BitArray, but obviously you could encapsulate these in a class that deals with categories.

这篇关于C#的值存储类别 - 位掩码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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