gpt4 book ai didi

C# 枚举排除

转载 作者:太空狗 更新时间:2023-10-29 19:56:18 25 4
gpt4 key购买 nike

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

[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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com