C# 枚举排除

标签 c# enums

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

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

假设我有一个变量定义为:

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

如何计算出所有未在“types”变量中定义的 NotificationMethodType 值?换句话说:

NotificationMethodType notAssigned = NotificationMethodType <that are not> types

最佳答案

如果类型列表永远不变,您可以这样做:

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

NotificationMethodType notAssigned = allTypes & ~types;

~ 通过反转所有位来创建一个反转值。

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

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

注意:如果您采用将 All 值添加到枚举的方法,请注意,如果 types 为空,您将不会获取一个将打印为“电子邮件、传真、短信”而不是“全部”的枚举。

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

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

或者您可以使用 LINQ 执行相同的操作:

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

这通过将枚举的所有单独值进行或运算来构建 allType 值。

关于C# 枚举排除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5377263/

相关文章:

vector - rust 是否可以为不同的数据结构提供统一的 Iterator 接口(interface)?

java - Switch 语句在 Java 中不适用于枚举

c# - 对您的实体实现跟踪更改的最佳方式是什么?

c# - 存储库类未在 ServiceStack 中处置

c# - 在编辑 mysql 数据库后运行某种脚本 C#

c++ - 模板结构中的枚举

grails - Redis(grails插件)不持久化枚举对象

c# - 选择列表返回 System.Data.Entity.DynamixProxies 而不是 MVC asp.net C# 中的值

c# - 从 C#/ASP.NET 应用程序将数据插入 SQL Server

JAVA - 更改成员枚举函数中的非静态类字段