Enum.HasFlag,为什么没有Enum.SetFlag?

时间:2011-05-01 19:45:22

标签: c# enums flags

我必须为我声明的每个标志类型构建一个扩展方法,如下所示:

public static EventMessageScope SetFlag(this EventMessageScope flags, 
    EventMessageScope flag, bool value)
{
    if (value)
        flags |= flag;
    else
        flags &= ~flag;

    return flags;
}

为什么Enum.SetFlag不存在Enum.HasFlag

另外,为什么这不起作用?

public static bool Get(this EventMessageScope flags, EventMessageScope flag)
{
    return ((flags & flag) != 0);
}

例如,如果我有:

var flag = EventMessageScope.Private;

并检查它:

if(flag.Get(EventMessageScope.Public))

EventMessageScope.Public确实是EventMessageScope.Private | EventMessageScope.PublicOnly,它返回true。

如果不是,因为Private不公开,只有一半公开。

同样适用:

if(flag.Get(EventMessageScope.None))

哪个返回false,但范围实际为None0x0),它应该始终返回true?

10 个答案:

答案 0 :(得分:32)

  

为什么没有像Enum.HasFlag这样的Enum.SetFlag?

HasFlag作为按位操作需要更复杂的逻辑并重复相同的标志两次

 myFlagsVariable=    ((myFlagsVariable & MyFlagsEnum.MyFlag) ==MyFlagsEnum.MyFlag );

所以MS决定实施它。

SetFlag和ClearFlag在C#中简洁

    flags |= flag;// SetFlag

    flags &= ~flag; // ClearFlag 

但不幸的是不直观。每当我需要设置(或清除)一个标志时,我会花费几秒钟(或几分钟)来思考:该方法的名称是什么?为什么它没有在intellisense中显示?或者不,我必须使用按位运算。注意,一些开发人员也会问:什么是按位操作?

应该创建SetFlag和ClearFlag扩展名 - YES显示在intellisense中。

开发人员是否应该使用SetFlag和ClearFlag扩展名 - 否,因为它们效率不高。

我们在库的类EnumFlagsHelper中创建了扩展,就像在 SomeEnumHelperMethodsThatMakeDoingWhatYouWantEasier,但将函数命名为SetFlag而不是Include和ClearFlag而不是Remove。

在SetFlag方法的主体中(以及摘要评论中)我决定添加

Debug.Assert( false, " do not use the extension due to performance reason, use bitwise operation with the explanatory comment instead \n 
flags |= flag;// SetFlag")

并且应该向ClearFlag添加类似的消息

Debug.Assert( false, " do not use the extension due to performance reason, use bitwise operation with the explanatory comment instead \n 
         flags &= ~flag; // ClearFlag  ")

答案 1 :(得分:10)

public static class SomeEnumHelperMethodsThatMakeDoingWhatYouWantEasier
{
    public static T IncludeAll<T>(this Enum value)
    {
        Type type = value.GetType();
        object result = value;
        string[] names = Enum.GetNames(type);
        foreach (var name in names)
        {
            ((Enum) result).Include(Enum.Parse(type, name));
        }

        return (T) result;
        //Enum.Parse(type, result.ToString());
    }

    /// <summary>
    /// Includes an enumerated type and returns the new value
    /// </summary>
    public static T Include<T>(this Enum value, T append)
    {
        Type type = value.GetType();

        //determine the values
        object result = value;
        var parsed = new _Value(append, type);
        if (parsed.Signed is long)
        {
            result = Convert.ToInt64(value) | (long) parsed.Signed;
        }
        else if (parsed.Unsigned is ulong)
        {
            result = Convert.ToUInt64(value) | (ulong) parsed.Unsigned;
        }

        //return the final value
        return (T) Enum.Parse(type, result.ToString());
    }

    /// <summary>
    /// Check to see if a flags enumeration has a specific flag set.
    /// </summary>
    /// <param name="variable">Flags enumeration to check</param>
    /// <param name="value">Flag to check for</param>
    /// <returns></returns>
    public static bool HasFlag(this Enum variable, Enum value)
    {
        if (variable == null)
            return false;

        if (value == null)
            throw new ArgumentNullException("value");

        // Not as good as the .NET 4 version of this function, 
        // but should be good enough
        if (!Enum.IsDefined(variable.GetType(), value))
        {
            throw new ArgumentException(string.Format(
                "Enumeration type mismatch.  The flag is of type '{0}', " +
                "was expecting '{1}'.", value.GetType(), 
                variable.GetType()));
        }

        ulong num = Convert.ToUInt64(value);
        return ((Convert.ToUInt64(variable) & num) == num);
    }


    /// <summary>
    /// Removes an enumerated type and returns the new value
    /// </summary>
    public static T Remove<T>(this Enum value, T remove)
    {
        Type type = value.GetType();

        //determine the values
        object result = value;
        var parsed = new _Value(remove, type);
        if (parsed.Signed is long)
        {
            result = Convert.ToInt64(value) & ~(long) parsed.Signed;
        }
        else if (parsed.Unsigned is ulong)
        {
            result = Convert.ToUInt64(value) & ~(ulong) parsed.Unsigned;
        }

        //return the final value
        return (T) Enum.Parse(type, result.ToString());
    }

    //class to simplfy narrowing values between
    //a ulong and long since either value should
    //cover any lesser value
    private class _Value
    {
        //cached comparisons for tye to use
        private static readonly Type _UInt32 = typeof (long);
        private static readonly Type _UInt64 = typeof (ulong);

        public readonly long? Signed;
        public readonly ulong? Unsigned;

        public _Value(object value, Type type)
        {
            //make sure it is even an enum to work with
            if (!type.IsEnum)
            {
                throw new ArgumentException(
                    "Value provided is not an enumerated type!");
            }

            //then check for the enumerated value
            Type compare = Enum.GetUnderlyingType(type);

            //if this is an unsigned long then the only
            //value that can hold it would be a ulong
            if (compare.Equals(_UInt32) || compare.Equals(_UInt64))
            {
                Unsigned = Convert.ToUInt64(value);
            }
                //otherwise, a long should cover anything else
            else
            {
                Signed = Convert.ToInt64(value);
            }
        }
    }
}

答案 2 :(得分:7)

我做了一些对我有用的事情,这很简单......

    public static T SetFlag<T>(this Enum value, T flag, bool set)
    {
        Type underlyingType = Enum.GetUnderlyingType(value.GetType());

        // note: AsInt mean: math integer vs enum (not the c# int type)
        dynamic valueAsInt = Convert.ChangeType(value, underlyingType);
        dynamic flagAsInt = Convert.ChangeType(flag, underlyingType);
        if (set)
        {
            valueAsInt |= flagAsInt;
        }
        else
        {
            valueAsInt &= ~flagAsInt;
        }

        return (T)valueAsInt;
    }

用法:

    var fa = FileAttributes.Normal;
    fa = fa.SetFlag(FileAttributes.Hidden, true);

答案 3 :(得分:3)

&运算符会为a & b提供与b & a相同的答案,因此

  

(EventMessaageScope.Private)。获取(EventMessageScope.Private | EventMessageScope.PublicOnly)

与写作相同

  

(EventMessageScope.Private | EventMessageScope.PublicOnly)。获取(EventMessaageScope.Private)

如果您只是想知道该值是否与EventMessaageScope.Public 相同,那么只需使用 equals

  

EventMessageScope.Private == EventMessageScope.Public

对于false,您的方法将始终返回(EventMessageScope.None).Get(EventMessaageScope.None)因为None == 0,并且只有当AND操作的结果为零时,它才会返回true。 0 & 0 == 0

答案 4 :(得分:1)

回答部分问题:Get函数根据二进制逻辑正常工作 - 它会检查是否有任何匹配。如果你想匹配整个标志集,请考虑改为:

return ((flags & flag) != flag);

关于“为什么不存在SetFlag”......可能是因为它并不是真的需要。标志是整数。已经有一个处理这些的约定,它也适用于标志。如果您不想使用|&来编写它 - 这就是自定义静态插件的用途 - 您可以在演示自己时使用自己的函数:)

答案 5 :(得分:1)

很久以前,Enums被C语言搞砸了。在C#语言中使用一些类型安全对于设计者来说很重要,当底层类型可以是字节和长字之间的任何东西时,没有空间容纳Enum.SetFlags。另一个C引发的问题顺便说一句。

处理它的正确方法是明确地内联编写这种代码,尝试将其推入扩展方法。您不希望用C#语言编写C宏。

答案 6 :(得分:1)

对于任何枚举,这是另一种快速而又脏的SetFlag方式:

public static T SetFlag<T>(this T flags, T flag, bool value) where T : struct, IComparable, IFormattable, IConvertible
    {
        int flagsInt = flags.ToInt32(NumberFormatInfo.CurrentInfo);
        int flagInt = flag.ToInt32(NumberFormatInfo.CurrentInfo);
        if (value)
        {
            flagsInt |= flagInt;
        }
        else
        {
            flagsInt &= ~flagInt;
        }
        return (T)(Object)flagsInt;
    }

答案 7 :(得分:0)

现在是 2021 年,C# 有很多不错的特性,这意味着应该有一种更优雅的方式来做到这一点。让我们讨论之前答案的主张...

权利要求 1: 关闭标志效率低下,因为它使用两个操作,而调用另一个方法只会增加更多开销。

这应该是假的。 如果添加 AggressiveInlining 编译器标志,编译器 应该 将按位运算提升为直接内联运算。如果您正在编写关键代码,您可能需要对此进行基准测试以确认,因为即使在不同的编译器版本之间,结果也会有所不同。但关键是,您应该能够调用方便的方法而无需支付方法查找成本。

权利要求 2: 它过于冗长,因为您必须设置标志然后分配返回值。

这也应该是假的。 C# 提供“ref”,它允许您通过引用直接操作值类型参数(在本例中为您的枚举)。结合 AggressiveInlining,编译器应该足够智能以完全删除 ref 指针,并且生成的 IL 看起来应该与您直接内联两个按位操作一样。

注意事项: 当然,这都是理论。也许其他人可以在这里的评论中出现并检查下面提议的代码中的 IL。我自己没有足够的经验(也没有现在的时间)来查看假设的主张是否属实。但我认为这个答案仍然值得发布,因为事实是 C#应该能够做我正在解释的事情。

如果其他人可以确认这一点,我可以相应地更新答案。

public enum MyCustomEnum : long
{
    NO_FLAGS            = 0,
    SOME_FLAG           = 1,
    OTHER_FLAG          = 1 << 1,
    YET_ANOTHER_FLAG    = 1 << 2,
    ANOTHER STILL       = 1 << 3
}

public static class MyCustomEnumExt
{
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void TurnOFF(ref this MyCustomEnum status, MyCustomEnum flag)
        => status &= ~flag;

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void TurnON(ref this MyCustomEnum status, MyCustomEnum flag)
        => status |= flag;
}

您应该能够像这样使用代码:

//Notice you don't have to return a value from the extension methods to assign manually.
MyCustomEnum mc = MyCustomEnum.SOME_FLAG;
mc.TurnOFF(MyCustomEnum.SOME_FLAG);
mc.TurnON(MyCustomEnum.OTHER_FLAG);

即使编译器未能正确优化它,它仍然非常方便。至少,您可以在非关键代码中使用它并期待出色的可读性。

答案 8 :(得分:0)

到目前为止的好答案,但如果您正在寻找不分配托管内存的更高效的速记,您可以使用这个:

using System;
using System.Runtime.CompilerServices;
public static class EnumFlagExtensions
{
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static TEnum AddFlag<TEnum>(this TEnum lhs, TEnum rhs) where TEnum : unmanaged, Enum
    {
        unsafe
        {
            switch (sizeof(TEnum))
            {
                case 1:
                    {
                        var r = *(byte*)(&lhs) | *(byte*)(&rhs);
                        return *(TEnum*)&r;
                    }
                case 2:
                    {
                        var r = *(ushort*)(&lhs) | *(ushort*)(&rhs);
                        return *(TEnum*)&r;
                    }
                case 4:
                    {
                        var r = *(uint*)(&lhs) | *(uint*)(&rhs);
                        return *(TEnum*)&r;
                    }
                case 8:
                    {
                        var r = *(ulong*)(&lhs) | *(ulong*)(&rhs);
                        return *(TEnum*)&r;
                    }
                default:
                    throw new Exception("Size does not match a known Enum backing type.");
            }
        }
    }
 
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static TEnum RemoveFlag<TEnum>(this TEnum lhs, TEnum rhs) where TEnum : unmanaged, Enum
    {
        unsafe
        {
            switch (sizeof(TEnum))
            {
                case 1:
                    {
                        var r = *(byte*)(&lhs) & ~*(byte*)(&rhs);
                        return *(TEnum*)&r;
                    }
                case 2:
                    {
                        var r = *(ushort*)(&lhs) & ~*(ushort*)(&rhs);
                        return *(TEnum*)&r;
                    }
                case 4:
                    {
                        var r = *(uint*)(&lhs) & ~*(uint*)(&rhs);
                        return *(TEnum*)&r;
                    }
                case 8:
                    {
                        var r = *(ulong*)(&lhs) & ~*(ulong*)(&rhs);
                        return *(TEnum*)&r;
                    }
                default:
                    throw new Exception("Size does not match a known Enum backing type.");
            }
        }
 
    }
 
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void SetFlag<TEnum>(ref this TEnum lhs, TEnum rhs) where TEnum : unmanaged, Enum
    {
        unsafe
        {
            fixed (TEnum* lhs1 = &lhs)
            {
                switch (sizeof(TEnum))
                {
                    case 1:
                        {
                            var r = *(byte*)(lhs1) | *(byte*)(&rhs);
                            *lhs1 = *(TEnum*)&r;
                            return;
                        }
                    case 2:
                        {
                            var r = *(ushort*)(lhs1) | *(ushort*)(&rhs);
                            *lhs1 = *(TEnum*)&r;
                            return;
                        }
                    case 4:
                        {
                            var r = *(uint*)(lhs1) | *(uint*)(&rhs);
                            *lhs1 = *(TEnum*)&r;
                            return;
                        }
                    case 8:
                        {
                            var r = *(ulong*)(lhs1) | *(ulong*)(&rhs);
                            *lhs1 = *(TEnum*)&r;
                            return;
                        }
                    default:
                        throw new Exception("Size does not match a known Enum backing type.");
                }
            }
        }
    }
 
    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static void ClearFlag<TEnum>(this ref TEnum lhs, TEnum rhs) where TEnum : unmanaged, Enum
    {
        unsafe
        {
            fixed (TEnum* lhs1 = &lhs)
            {
                switch (sizeof(TEnum))
                {
                    case 1:
                        {
                            var r = *(byte*)(lhs1) & ~*(byte*)(&rhs);
                            *lhs1 = *(TEnum*)&r;
                            return;
                        }
                    case 2:
                        {
                            var r = *(ushort*)(lhs1) & ~*(ushort*)(&rhs);
                            *lhs1 = *(TEnum*)&r;
                            return;
                        }
                    case 4:
                        {
                            var r = *(uint*)(lhs1) & ~*(uint*)(&rhs);
                            *lhs1 = *(TEnum*)&r;
                            return;
                        }
                    case 8:
                        {
                            var r = *(ulong*)(lhs1) & ~*(ulong*)(&rhs);
                            *lhs1 = *(TEnum*)&r;
                            return;
                        }
                    default:
                        throw new Exception("Size does not match a known Enum backing type.");
                }
            }
        }
    }
}

它只需要 C# 7.3 或更高版本,并指示编译器接受 /unsafe 代码。

AddFlag 和 RemoveFlag 不会修改您调用它的枚举值,SetFlag 和 ClearFlag 会修改它。这可能是性能开销最低的通用解决方案,但仍然不如直接使用

flags |= flag;
flags &= ~flag;

答案 9 :(得分:-1)

我找到的原因是因为枚举是一种值类型,所以你不能传入它并设置它的类型。对于那些认为它很愚蠢的人,我这样对你说:并非所有开发人员都理解位标志以及如何打开或关闭它们(这更不直观)。

不是一个愚蠢的想法,只是不可能。

相关问题