用于序列化/反序列化一组标志的内置类

时间:2023-01-15 19:00:29

I need to store an array of flags in a string. I was looking at using BitArray, but noticed that there is no built-in method to write to/read from a char[] or int[] or something. I can write this code easily enough, but I'd prefer to use a built-in method if there is one out there.

我需要在字符串中存储一组标志。我正在寻找使用BitArray,但注意到没有内置方法来写入/读取char []或int []或其他东西。我可以很容易地编写这段代码,但如果有一个内置方法,我宁愿使用内置方法。

So are there built-in .NET methods that handle this?

那么有内置的.NET方法来处理这个问题吗?

3 个解决方案

#1


If your flags are represented as a defined enum, you can simply cast it to one of the integral types that enums support (int, long, etc). You can then deserialize the enum from its value representation using:

如果您的标志表示为已定义的枚举,您只需将其强制转换为枚举支持的整数类型之一(int,long等)。然后,您可以使用以下命令从其值表示中反序列化枚举:

// define a Flags enumeration...
[Flags] enum MyEnum { First = 1, Second = 2, Third = 4, };


MyEnum originalValue = MyEnum.First | MyEnum.Second;
int storedValue = (int)originalValue;  

// value serialized into storage somewhere...

// later on ...
// deserialized however you need...
int restoredValue = ReadValueFromDataStore(); 
// convert back into a typesafe enum...
MyEnum recoveredValue = Enum.Parse( typeof(MyEnum), restoredValue );

#2


The BitConverter class has some of this functionality.

BitConverter类具有一些此功能。

#3


The BitArray does support Int32[], you can use the constructor that accepts an int[] for initialization, and CopyTo(Array array, Int32 index). The current CopyTo implementation supports writing to Boolean[], Byte[] and Int32[] according to msdn.

BitArray支持Int32 [],您可以使用接受int []进行初始化的构造函数,以及CopyTo(Array数组,Int32索引)。根据msdn,当前的CopyTo实现支持写入Boolean [],Byte []和Int32 []。

#1


If your flags are represented as a defined enum, you can simply cast it to one of the integral types that enums support (int, long, etc). You can then deserialize the enum from its value representation using:

如果您的标志表示为已定义的枚举,您只需将其强制转换为枚举支持的整数类型之一(int,long等)。然后,您可以使用以下命令从其值表示中反序列化枚举:

// define a Flags enumeration...
[Flags] enum MyEnum { First = 1, Second = 2, Third = 4, };


MyEnum originalValue = MyEnum.First | MyEnum.Second;
int storedValue = (int)originalValue;  

// value serialized into storage somewhere...

// later on ...
// deserialized however you need...
int restoredValue = ReadValueFromDataStore(); 
// convert back into a typesafe enum...
MyEnum recoveredValue = Enum.Parse( typeof(MyEnum), restoredValue );

#2


The BitConverter class has some of this functionality.

BitConverter类具有一些此功能。

#3


The BitArray does support Int32[], you can use the constructor that accepts an int[] for initialization, and CopyTo(Array array, Int32 index). The current CopyTo implementation supports writing to Boolean[], Byte[] and Int32[] according to msdn.

BitArray支持Int32 [],您可以使用接受int []进行初始化的构造函数,以及CopyTo(Array数组,Int32索引)。根据msdn,当前的CopyTo实现支持写入Boolean [],Byte []和Int32 []。