c#enum exclude

awi*_*nsk 8 c# enums

假设我有一个这样的枚举:

[Flags]
public enum NotificationMethodType {
    Email = 1,
    Fax = 2,
    Sms = 4
}
Run Code Online (Sandbox Code Playgroud)

让我们说我有一个变量定义为:

NotificationMethodType types = (NotificationMethodType.Email | NotificationMethodType.Fax)
Run Code Online (Sandbox Code Playgroud)

如何计算未在"types"变量中定义的所有NotificationMethodType值?换一种说法:

NotificationMethodType notAssigned = NotificationMethodType <that are not> types
Run Code Online (Sandbox Code Playgroud)

ang*_*son 15

如果类型列表永远不会更改,则可以执行以下操作:

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

NotificationMethodType notAssigned = allTypes & ~types;
Run Code Online (Sandbox Code Playgroud)

〜通过反转所有位来创建反转值.

定义此类枚举以至少将"allTypes"的定义保持为枚举本地的典型方法是在枚举中包含两个新名称:

[Flags]
public enum NotificationMethodType {
    None = 0,
    Email = 1,
    Fax = 2,
    Sms = 4,
    All = Email | Fax | Sms
}
Run Code Online (Sandbox Code Playgroud)

注意:如果您将All值添加到枚举的路径,请注意,如果types为空,您将不会得到打印为"电子邮件,传真,短信" 的枚举,而是"全部".

如果您不想手动维护列表allTypes,可以使用以下Enum.GetValues方法:

NotificationMethodType allTypes = 0;
foreach (NotificationMethodType type in Enum.GetValues(typeof(NotificationMethodType)))
    allTypes |= type;
Run Code Online (Sandbox Code Playgroud)

或者你也可以用LINQ做同样的事情:

NotificationMethodType allTypes = 
    Enum.GetValues(typeof(NotificationMethodType))
    .Cast<NotificationMethodType>()
    .Aggregate ((current, value) => current | value);
Run Code Online (Sandbox Code Playgroud)

allType通过将枚举的所有单个值进行OR运算来构建值.