如果您使用声明过载或可选参数在C#4.0的方法呢? [英] Should you declare methods using overloads or optional parameters in C# 4.0?

查看:126
本文介绍了如果您使用声明过载或可选参数在C#4.0的方法呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正要C#4.0看 Anders的谈话和潜行$的C#5.0 p $ PVIEW,它得到了我想,当可选参数在C#中正在发生的事情是,宣布不需要所有参数的方法推荐的方法使用指定的?

I was watching Anders' talk about C# 4.0 and sneak preview of C# 5.0, and it got me thinking about when optional parameters are available in C# what is going to be the recommended way to declare methods that do not need all parameters specified?

例如像在的FileStream 类大约有十五种不同的构造可分为逻辑家庭例如从字符串下面的人,从的IntPtr 的那些,并从那些在 SafeFileHandle

For example something like the FileStream class has about fifteen different constructors which can be divided into logical 'families' e.g. the ones below from a string, the ones from an IntPtr and the ones from a SafeFileHandle.

FileStream(string,FileMode);
FileStream(string,FileMode,FileAccess);
FileStream(string,FileMode,FileAccess,FileShare);
FileStream(string,FileMode,FileAccess,FileShare,int);
FileStream(string,FileMode,FileAccess,FileShare,int,bool);

在我看来,这种模式可以通过有三个构造来代替,并使用可选的参数,可以拖欠的那些,这将使构造的不同系列的更加鲜明【注意事项进行简化:我知道这个变化不会在BCL提出,我说的是假设这种类型的情况。

It seems to me that this type of pattern could be simplified by having three constructors instead, and using optional parameters for the ones that can be defaulted, which would make the different families of constructors more distinct [note: I know this change will not be made in the BCL, I'm talking hypothetically for this type of situation].

你觉得呢?从C#4.0会更有意义,使构造函数和方法具有可选参数的单一方法密切相关的群体,或者是有一个很好的理由坚持使用传统的许多超载的机制?

What do you think? From C# 4.0 will it make more sense to make closely related groups of constructors and methods a single method with optional parameters, or is there a good reason to stick with the traditional many-overload mechanism?

推荐答案

我会考虑以下几点:


  • 请您需要从语言中使用您的code不支持可选参数?如果是的话,可以考虑包括过载。

  • 请您对您的团队成员任谁反对暴力可选参数? (有时更容易忍受你不比据理力争喜欢的决定。)

  • 您相信,如果搞不好你的默认设置不会更改建立你code之间,或者将您的来电没事与?

我没有检查的默认设置将如何工作,但我会假设默认值将被烤成调用code,一样一样的引用常量字段。这通常没关系 - 更改为默认值是pretty反正显著 - 但这些都是要考虑的事情。

I haven't checked how the defaults are going to work, but I'd assume that the default values will be baked into the calling code, much the same as references to const fields. That's usually okay - changes to a default value are pretty significant anyway - but those are the things to consider.

这篇关于如果您使用声明过载或可选参数在C#4.0的方法呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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