开发者

c# enum exclude

Let's say I have an enum like this:

[Flags]
public enum NotificationMethodType {
    Email = 1,
    Fax = 2,
    Sms = 4
}

And let's sa开发者_如何学Pythony I have a variable defined as:

NotificationMethodType types = (NotificationMethodType.Email | NotificationMethodType.Fax)

How do I figure out all of the NotificationMethodType values that are not defined in the "types" variable? In other words:

NotificationMethodType notAssigned = NotificationMethodType <that are not> types


If the list of types never changes, you can do this:

NotificationMethodType allTypes = NotificationMethodType.Email |
    NotificationMethodType.Fax |
    NotificationMethodType.Sms;

NotificationMethodType notAssigned = allTypes & ~types;

The ~ creates an inverse value, by inverting all the bits.

A typical way to define such enums to at least keep the definition of "allTypes" local to the enum would be to include two new names into the enum:

[Flags]
public enum NotificationMethodType {
    None = 0,
    Email = 1,
    Fax = 2,
    Sms = 4,
    All = Email | Fax | Sms
}

Note: If you go the route of adding the All value to the enum, note that if types was empty, you would not get an enum that would print as "Email, Fax, Sms", but rather as "All".

If you don't want to manually maintain the list of allTypes, you can do it using the Enum.GetValues method:

NotificationMethodType allTypes = 0;
foreach (NotificationMethodType type in Enum.GetValues(typeof(NotificationMethodType)))
    allTypes |= type;

or you can do the same with LINQ:

NotificationMethodType allTypes = 
    Enum.GetValues(typeof(NotificationMethodType))
    .Cast<NotificationMethodType>()
    .Aggregate ((current, value) => current | value);

This builds the allType value by OR'ing together all the individual values of the enum.


A simple XOR will do the trick...

NotificationMethodType all = (NotificationMethodType.Email | NotificationMethodType.Fax | NotificationMethodType.Sms);
NotificationMethodType used = (NotificationMethodType.Email | NotificationMethodType.Fax);
NotificationMethodType unused = (all ^ used);

To make this a little cleaner, add the All value to your enum definition directly (set value to 7 obviously). This way, you can add things to the enum later without breaking this code


var notAssigned = Enum.GetValues(typeof(NotificationMethodType))
                      .Cast<NotificationMethodType>()
                      .Where(x => !types.HasFlag(x))
                      .Aggregate((a, x) => a | x);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜