时间:2019-01-17 标签:c#enumexclusive
假设我有一个像这样的枚举:
[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
Let's say I have an enum like this:
[Flags]
public enum NotificationMethodType {
Email = 1,
Fax = 2,
Sms = 4
}
And let's say 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果类型列表永远不会改变,您可以这样做:
~ 通过反转所有位来创建一个反转值。
定义此类枚举以至少将“allTypes”的定义保留在枚举本地的典型方法是在枚举中包含两个新名称:
注意:如果您选择添加 < code>All 值赋给枚举,请注意,如果
types
为空,您将不会得到一个可以打印为“电子邮件、传真、短信”的枚举,而是“全部”。如果您不想手动维护
allTypes
列表,可以使用Enum.GetValues
方法来完成:或者您可以使用 LINQ 执行相同操作:
此构建通过将枚举的所有单独值进行或运算来得到
allType
值。If the list of types never changes, you can do this:
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:
Note: If you go the route of adding the
All
value to the enum, note that iftypes
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 theEnum.GetValues
method:or you can do the same with LINQ:
This builds the
allType
value by OR'ing together all the individual values of the enum.一个简单的 XOR 就可以解决问题...
为了使其更简洁,请将 All 值直接添加到您的枚举定义中(显然将值设置为 7)。这样,您可以稍后将内容添加到枚举中,而不会破坏此代码
A simple XOR will do the trick...
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