开发者

How do I use unsafe values in an enum?

开发者 https://www.devze.com 2022-12-26 07:09 出处:网络
I need to use this enum in my C# application, but it won\'t let me use these values. When I specify the type as uint I can use the -1 value, and when I specify int I can\'t use the last 2 values. Is t

I need to use this enum in my C# application, but it won't let me use these values. When I specify the type as uint I can use the -1 value, and when I specify int I can't use the last 2 values. Is there a way to use the unchecked keyword her开发者_运维技巧e to allow me to define all of these values? These values are coming from an external source, so I can't change them.

internal enum MyValues : int
{
    value1 = -1,
    value2 = 0,
    value3 = 0x80000000,
    value4 = 0xFFFFFFFF
}


If you want -1 to be a different value from 0xFFFFFFFF, you're going to need a datatype bigger than 32 bits. Try long.


0xFFFFFFFF is a 32 bit number, so it should be fit to enum : int ( I feel long type is an overkill :) )

Have you tried

enum YourEnum : int { /*...*/, value4 = unchecked( (int)0xFFFFFFFF ) };


One way to solve this is to use normal values for the enum (0, 1, 2, 3), and create a class or a pair of methods to convert the incoming values to the enum members and vice-versa.


Since these values look to be constant, just create a static class to hold the values. Also, you can use whatever types you want:

public static class MyValues
{
    public const int value1 = -1;
    public const int value2= 0;
    public const int value3 = 0x80000000;
    public const int value4 = 0xFFFFFFFF;
}


Maybe try ulong enums instead of int?

0

精彩评论

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

关注公众号