BCL 中是否存在用于启用/禁用的(隐藏良好的)通用枚举?
因此,我只是讨厌使用true
/false
作为“启用”/“禁用”的方法参数。自由地引用杰夫的话:“我从根本上不喜欢它”。
我反复发现自己在各地不同命名空间中的每个新项目中定义自己的枚举,例如:
public enum Clickability
{
Disabled,
Enabled
}
public enum Editability
{
Disabled,
Enabled
}
public enum Serializability
{
Disabled,
Enabled
}
是否有一个通用枚举可以用于这些场景?
So, I just hate using true
/false
as method arguments for "enabled"/"disabled". To freely quote Jeff: "I dislike it on a fundamental level".
I repeatedly find myself defining my own enums on every new project in different namespaces all over the place, like these:
public enum Clickability
{
Disabled,
Enabled
}
public enum Editability
{
Disabled,
Enabled
}
public enum Serializability
{
Disabled,
Enabled
}
Is there a generic enum I can use for these scenarios?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这样做的问题是,它实际上对真正有问题的情况没有帮助,即当存在多个参数并且不清楚“标志”控制什么时。
如果您遵循“避免双重否定”的规则,那么简单的单个布尔值就可以了:
然后
Foo(true)
,诗句Foo(Ability.Enabled)
和Foo(false)
,Foo(Ability.Disabled)
的经文对大多数人来说确实非常明显。然而,当你点击这样的方法时:
那么无论你使用布尔值还是通用枚举,它们最终在调用站点上都会看起来像这样:
两者都不漂亮。
对于手头的情况使用特定枚举:
那么你会得到
或者,如果所有都是简单的布尔状态并且可能保持这样,那么使用标记枚举更好。
然后您将:
适当选择“活动”标志,以便您仅指定不常见的内容,然后将突出显示“不常见”用法。
The problem with this is that it doesn't actually help in the real problematic cases which is when there are multiple arguments and it is not clear what the 'flag' is controlling.
If you follow the rule that you should 'avoid double negatives' then simple single booleans are fine:
Then
Foo(true)
, versesFoo(Ability.Enabled)
andFoo(false)
, versesFoo(Ability.Disabled)
are really pretty obvious to most.However when you hit a method like:
then it matters not whether you use booleans or general enums they still both end up looking like this at the call site:
Neither is pretty.
Using specific enumerations for the case in hand:
then you get
or, if all are simple boolean states and likely to remain so then using a Flagged enumeration better still.
Then you would have:
Appropriate selection of the 'active' flags so that you specify only what is uncommon will then lead to highlighting 'uncommon' usages.
不,BCL 中没有这样的枚举(据我所知)。但是,采用您重复创建的其中之一并使其更加通用并不难:
将其放入具有类似通用内容的某个类库中,并在您的项目中重用它。
No, there is no such enum in the BCL (to the best of my knowledge). But it's not hard to take one of those that you repeatedly create and make it more general:
Stick it into some class library with similarly general stuff, and reuse it in your projects.
使用具有有意义名称的
bool
参数有什么问题?或者,更好的是,一些不那么冗长的东西:
我会发现这比大量
enum
参数更具可读性。What's wrong with using
bool
parameters with meaningful names?Or, better still, something a bit less verbose:
I would find this much more readable than loads of
enum
parameters.