如何将枚举值转换为压缩字符串?
我有一个枚举,其定义如下:
[Flags]
public enum MyEnum
{
None = 0,
ValueOne = 1 << 0,
ValueTwo = 1 << 1,
ValueThree = 1 << 2,
ValueFour = 1 << 3,
...
ValueTwoEightyOne = 1 << 280,
}
我希望能够将用法转换为可能的最短字符串,类似于:
var compressedString = ConvertToCompressedString(MyEnum.ValueOne | MyEnum.ValueThree | MyEnum.ValueFour);
然后在程序的不同部分,我想将compressedString 转换回枚举
var enumValue = ConvertBack(compressedString);
什么是转换具有如此多值的枚举的有效方法?如果有更好的方法来处理此类用例,我很感兴趣。
I have an enum that is defined like:
[Flags]
public enum MyEnum
{
None = 0,
ValueOne = 1 << 0,
ValueTwo = 1 << 1,
ValueThree = 1 << 2,
ValueFour = 1 << 3,
...
ValueTwoEightyOne = 1 << 280,
}
I would like to be able to convert usage to the shortest string possible, similar to:
var compressedString = ConvertToCompressedString(MyEnum.ValueOne | MyEnum.ValueThree | MyEnum.ValueFour);
And then in a different part of the program, I would like to convert the compressedString back to the enum
var enumValue = ConvertBack(compressedString);
What is an efficient method to convert an enum with so many values? If there is a better way of handling this type of use case, I'm interested.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
enum
值由内存中的整数字段支持。那么除了整数本身之外,您还需要什么更多的压缩呢?但要小心,因为 1 << 280 (2^280) 是一个相当大的数字,无法存储在
Int32
甚至Int64
中。enum
values are backed by an integer field in memory. So what more compression you need than the integer itself?But be careful because 1 << 280 (2^280) is a pretty large number that cannot be stored in an
Int32
or evenInt64
.如果我需要一个具有超过 64 个标志的“标志枚举”,我可能会仅使用枚举来表示位索引,然后将 BitArray 包装在类中以保存值。
要获得紧凑的表示形式,可以将位数组转换为字节数组。我从代码中省略了该步骤,但您可以执行例如 像这样(注意字节序!)
If I needed a "Flags enum" with more than 64 flags, I'd probably use an enum for only the bit indices, and then wrap a BitArray inside a class to hold the values.
To get the compact representation, you can convert the bit array to a byte array. I omitted that step from the code, but you can do e.g. like this (pay attention to the endianness!)