.NET:布尔VS枚举方法参数 [英] .NET: bool vs enum as a method parameter

查看:164
本文介绍了.NET:布尔VS枚举方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每个时间我正在写一个方法,需要一个布尔参数重新presenting一种选择,我发现自己在想:我应该用一个枚举这将使得替代这种阅读方法调用更容易?<。 / P>

考虑使用一个对象,它需要一个参数告诉实现是否应该利用其线程安全的版本,或不(我不问这里如果这样做这是好的设计或没有,只有使用以下布尔):

 公共无效CreateSomeObject(布尔makeThreadSafe);
CreateSomeObject(真正的);
 

在电话旁边是参数的目的似乎当然很明显的声明。当它在一些第三方库,你几乎不知道,这是很难立即看到什么code的确,比起:

 公开枚举CreationOptions {无,MakeThreadSafe}
公共无效CreateSomeObject(CreationOptions选项);
CreateSomeObject(CreationOptions.MakeThreadSafe);
 

描述的意图好得多。

在事态进一步恶化时,有两个布尔重新presenting选项参数。看看发生了什么,以 ObjectContext.SaveChanges(布尔)框架3.5和4.0之间。它已被废弃,因为第二个选项已被引入,整个事情已经转化为一个枚举。

虽然看起来很明显使用枚举时,有三个要素或更多,你有什么意见和有关使用一个枚举,而不是一个布尔值在这些特定情况下的经验?

解决方案

.NET 4.0可能会有所帮助。您可以使用命名参数:

  CreateSomeObject(makeThreadSafe:真正的);
 

对于老版本中,它可能是有用的,而不是创建临时变量。

 布尔makeThreadSafe = TRUE;
CreateSomeObject(makeThreadSafe);
 

Each time I'm writing a method that takes a boolean parameter representing an option, I find myself thinking: "should I replace this by an enum which would make reading the method calls much easier?".

Consider the following with an object that takes a parameter telling whether the implementation should use its thread-safe version or not (I'm not asking here if this way of doing this is good design or not, only the use of the boolean):

public void CreateSomeObject(bool makeThreadSafe);
CreateSomeObject(true);

When the call is next to the declaration the purpose of the parameter seems of course obvious. When it's in some third party library you barely know, it's harder to immediately see what the code does, compared to:

public enum CreationOptions { None, MakeThreadSafe }
public void CreateSomeObject(CreationOptions options);
CreateSomeObject(CreationOptions.MakeThreadSafe);

which describes the intent far better.

Things get worse when there's two boolean parameters representing options. See what happened to ObjectContext.SaveChanges(bool) between Framework 3.5 and 4.0. It has been obsoleted because a second option has been introduced and the whole thing has been converted to an enum.

While it seems obvious to use an enumeration when there's three elements or more, what's your opinion and experiences about using an enum instead a boolean in these specific cases?

解决方案

.NET 4.0 might help here. You can use named parameters:

CreateSomeObject(makeThreadSafe : true);

For older versions it can be useful to create temporary variables instead.

bool makeThreadSafe = true;
CreateSomeObject(makeThreadSafe);

这篇关于.NET:布尔VS枚举方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆