将枚举映射到 [Flags] 枚举
我有一个枚举,假设:
public enum ItemStatus {
Available, Unavailable
}
我有一个基于过滤器返回这些电视列表的方法。过滤器由 Enum 表示:
[Flags]
public enum ItemStatusFilter {
Available = 1, Unavailable = 2
}
问题:检查给定的 ItemStatus 实例是否与给定的 ItemStatusFilter 实例匹配的巧妙方法是什么?
我不喜欢为 ItemStatus 成员 (1,2) 赋值的想法,因为该枚举不需要它。现在我的代码如下所示:
public static bool Matches(this TagStatusFilter statusFilter, TagStatus status) {
if (status == TagStatus.Available && ((statusFilter & TagStatusFilter.Available) != 0)) return true;
if (status == TagStatus.Unavailable && ((statusFilter & TagStatusFilter.Unavailable) != 0)) return true;
return false;
}
沿着这些思路怎么样?
[Flags]
public enum TagStatusFilter {
Available = 1 << TagStatus.Available,
Unavailable = 1 << TagStatus.Unavailable
}
目标是减少代码量并减少类型之间的耦合。
是不是感觉这里滥用了 enum TagStatusFilter
?
I have an Enum, suppose:
public enum ItemStatus {
Available, Unavailable
}
I have a method that returns a list of those TVs, based on a filter. And a filter is represented by an Enum:
[Flags]
public enum ItemStatusFilter {
Available = 1, Unavailable = 2
}
Question: what is a slick way to check if given instance of ItemStatus matches given instance of ItemStatusFilter?
I dislike the idea of assigning values to ItemStatus members (1,2) since it is not required by that enum. Right now my code looks as follows:
public static bool Matches(this TagStatusFilter statusFilter, TagStatus status) {
if (status == TagStatus.Available && ((statusFilter & TagStatusFilter.Available) != 0)) return true;
if (status == TagStatus.Unavailable && ((statusFilter & TagStatusFilter.Unavailable) != 0)) return true;
return false;
}
What about something along these lines?
[Flags]
public enum TagStatusFilter {
Available = 1 << TagStatus.Available,
Unavailable = 1 << TagStatus.Unavailable
}
The goal is to reduce amount of code, and reduce coupling between types.
Does it feel like enum TagStatusFilter
is misused here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不喜欢它..但它会起作用:
i don't like it.. but it'll work:
如果你想使用标志属性,你可以使用按位运算。我写了一篇关于此的博客文章,希望对您有用。
http://ehsanghanbari.com /Post/86/为什么枚举值是网络中的位标志
you can use bit wise operation, if you want to use flag attribute. I've written a blog post about this, I hope it could be useful for you.
http://ehsanghanbari.com/Post/86/why-the-values-of-enums-are-bit-flag-in-net
如果两个枚举仅在
[Flag]
属性上不同,那么您可以用于过滤IEnumerable
类型。所以你有充分的理由使用两个枚举,然后最好用
If two enums differs only in
[Flag]
attribute, then you can use for filteringIEnumerable<ItemStatus>
type.So you have strong reasons to use two enums then it better to filter with