获取盒装枚举的整数值

发布于 2024-07-17 14:36:13 字数 2442 浏览 6 评论 0原文

我决定不可能通过反射执行以下(等效)枚举操作 - 因为 Enum 类没有运算符,并且发出的代码也不公开任何运算符:

object boxedEnum = MyEnum.Flag1 | MyEnum.Flag2;
boxedEnum &= ~MyEnum.Flag2; // Remove the flag.

所以我目前正在执行以下(等效)操作:

int boxedEnumValue = (int) boxedEnum;
boxedEnumValue &= ~MyEnum.Flag2;
boxedEnum = Enum.ToObject(boxedEnum.GetType(), boxedEnumValue);

哪个工作正常,唯一的问题是,将 boxedEnum 转换为整数的等效代码是:

int boxedEnumValue = int.Parse(Enum.Format(boxedEnum.GetType(), boxedEnum, "X"), System.Globalization.NumberStyles.HexNumber);

我相信您会同意这是可怕和黑客的。

所以这个问题有两个方面。 如果有人能证明我错了并提供一种对盒装枚举执行二进制操作的方法,那就太棒了 - 否则任何避免字符串往返的方法将不胜感激。

Guffa 给了我我需要的东西为了将枚举转换为特定类型。 我编写了一个扩展方法来处理具体问题:

    /// <summary>
    /// Gets the integral value of an enum.
    /// </summary>
    /// <param name="value">The enum to get the integral value of.</param>
    /// <returns></returns>
    public static T ToIntegral<T>(this object value)
    {
        if(object.ReferenceEquals(value, null))
            throw new ArgumentNullException("value");
        Type rootType = value.GetType();
        if (!rootType.IsEnum)
            throw new ArgumentOutOfRangeException("value", "value must be a boxed enum.");
        Type t = Enum.GetUnderlyingType(rootType);

        switch (t.Name.ToUpperInvariant())
        {
            case "SBYTE":
                return (T)Convert.ChangeType((sbyte) value, typeof(T));
            case "BYTE":
                return (T) Convert.ChangeType((byte) value, typeof(T));
            case "INT16":
                return (T) Convert.ChangeType((Int16) value, typeof(T));
            case "UINT16":
                return (T) Convert.ChangeType((UInt16) value, typeof(T));
            case "INT32":
                return (T) Convert.ChangeType((Int32) value, typeof(T));
            case "UINT32":
                return (T) Convert.ChangeType((UInt32) value, typeof(T));
            case "INT64":
                return (T) Convert.ChangeType((Int64) value, typeof(T));
            case "UINT64":
                return (T) Convert.ChangeType((UInt64) value, typeof(T));
            default:
                throw new NotSupportedException();
        }
    }

I have decided it is impossible to do the following (equivalent) enum operations via reflection - as the Enum class has no operators, and nor does the emitted code expose any operators:

object boxedEnum = MyEnum.Flag1 | MyEnum.Flag2;
boxedEnum &= ~MyEnum.Flag2; // Remove the flag.

So I am currently doing the following (equivalent):

int boxedEnumValue = (int) boxedEnum;
boxedEnumValue &= ~MyEnum.Flag2;
boxedEnum = Enum.ToObject(boxedEnum.GetType(), boxedEnumValue);

Which works fine, the only problem is that the equivalent code to turn the boxedEnum into an integer is:

int boxedEnumValue = int.Parse(Enum.Format(boxedEnum.GetType(), boxedEnum, "X"), System.Globalization.NumberStyles.HexNumber);

Which I am sure you will agree is terrible and hacky.

So this question has two prongs. It would be awesome if someone could prove me wrong and provide a means to perform binary operations on boxed enums - otherwise any way to avoid the string round-trip would be appreciated.

Guffa gave me what I needed in order to convert the enum to a specific type. I authored an extension method that does the nitty-gritties:

    /// <summary>
    /// Gets the integral value of an enum.
    /// </summary>
    /// <param name="value">The enum to get the integral value of.</param>
    /// <returns></returns>
    public static T ToIntegral<T>(this object value)
    {
        if(object.ReferenceEquals(value, null))
            throw new ArgumentNullException("value");
        Type rootType = value.GetType();
        if (!rootType.IsEnum)
            throw new ArgumentOutOfRangeException("value", "value must be a boxed enum.");
        Type t = Enum.GetUnderlyingType(rootType);

        switch (t.Name.ToUpperInvariant())
        {
            case "SBYTE":
                return (T)Convert.ChangeType((sbyte) value, typeof(T));
            case "BYTE":
                return (T) Convert.ChangeType((byte) value, typeof(T));
            case "INT16":
                return (T) Convert.ChangeType((Int16) value, typeof(T));
            case "UINT16":
                return (T) Convert.ChangeType((UInt16) value, typeof(T));
            case "INT32":
                return (T) Convert.ChangeType((Int32) value, typeof(T));
            case "UINT32":
                return (T) Convert.ChangeType((UInt32) value, typeof(T));
            case "INT64":
                return (T) Convert.ChangeType((Int64) value, typeof(T));
            case "UINT64":
                return (T) Convert.ChangeType((UInt64) value, typeof(T));
            default:
                throw new NotSupportedException();
        }
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

放我走吧 2024-07-24 14:36:13

装箱值永远无法就地更改。 您只需取消装箱枚举,执行操作并再次装箱:

boxedEnum = (MyEnum)boxedEnum & ~MyEnum.Flag2;

编辑:

如果枚举的基础类型是 int,您可以将其取消装箱为 int,然后将其装箱为 int。 装箱的 int 稍后可以拆箱为枚举类型:

boxedEnum = (int)boxedEnum & ~2;

MyEnum value = (MyEnum)boxedEnum; // works both for a boxed int and a boxed MyEnum

A boxed value can never be changed in place. You just have to unbox the enum, do the operation and box it again:

boxedEnum = (MyEnum)boxedEnum & ~MyEnum.Flag2;

Edit:

Provided that the underlying type of the enum is int, you can just unbox it to int and box it to int. The boxed int can later on be unboxed to the enum type:

boxedEnum = (int)boxedEnum & ~2;

MyEnum value = (MyEnum)boxedEnum; // works both for a boxed int and a boxed MyEnum
℡Ms空城旧梦 2024-07-24 14:36:13
int enumValue = (int)SomeEnum.Val1 | (int)SomeEnum.Val2;
SomeEnum e = (SomeEnum)enumValue;

你想实现这样的目标吗?

int enumValue = (int)SomeEnum.Val1 | (int)SomeEnum.Val2;
SomeEnum e = (SomeEnum)enumValue;

Do you want to achieve something like this?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文