简体   繁体   中英

C# Extending all [Flag] enums?

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

public static void Set(this EventFlags flags, EventFlags flag, bool value)
{
    if (value)
        flags |= flag;
    else
        flags &= ~flag;
}

basically I want to do that for any [Flag] enum, for instance

[Flags]
public enum FlagEn
{
   None = 0x0000,
   UseSkill = 0x0001
}

What you really want is a generic method with an enum constraint. However, C# doesn't allow that.

Fortunately, the CLR does allow it, and with a little hackery you can use a library to get goodness like this - although I should point out that your Set method currently doesn't actually do anything - you should really make it return the value after computing it.

I have a library for precisely this sort of thing which you might want to look at: Unconstrained Melody . Note that even with the hackery, the constraint can't enforce at compile time that you're actually calling it on a flags enum and not some other enum. (I do provide execution-time checking though.)

For what you're after, I suggest you look at the Flags class - in particular the Or , HasAny and HasAll methods.

不,您不能,因为没有FlagEnum类的东西,只有具有Flag属性的enum

You could try the following:

public static class EnumExtensions
{
    public static bool Get(this Enum theEnum, Enum flag)
    {
        var flagsAttributes = theEnum.GetType().GetCustomAttributes(typeof(FlagsAttribute), false);
        if (flagsAttributes.Length == 0)
            return false; // not a [Flags] enum

        return theEnum.HasFlag(flag);
    }
}

You could consider returning a bool? instead and return null when the enum doesn't have the [Flags] attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM