您应该在 C# 4.0 中使用重载还是可选参数来声明方法? [英] Should you declare methods using overloads or optional parameters in C# 4.0?

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

问题描述

我正在观看 Anders 关于 C# 4.0 和 C# 5.0 的预览,并且这让我开始思考,当可选参数在 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 类有大约 15 个不同的构造函数,它们可以分为逻辑家族",例如下面的那些来自字符串,来自 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?

推荐答案

我会考虑以下几点:

  • 您是否需要在不支持可选参数的语言中使用您的代码?如果是这样,请考虑包括重载.
  • 您的团队中是否有成员强烈反对可选参数?(有时接受一个你不喜欢的决定比争论这个案子更容易.)
  • 您是否确信您的默认设置不会在您的代码构建之间发生变化,或者如果可能,您的调用者会同意吗?

我还没有检查默认值将如何工作,但我假设默认值将被烘焙到调用代码中,与对 const 字段的引用非常相似.这通常没问题 - 对默认值的更改无论如何都非常重要 - 但这些都是需要考虑的事情.

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天全站免登陆