我什么时候应该考虑对普通参数使用命名参数?
我将 RenameFolder 分成两部分,我注意到 Visual Studios 2010 支持命名参数! (下面的例子)。
我知道这在其他语言中已经存在很多年了。我记得一位教授说过他为什么喜欢命名参数以及他在所有代码中都使用它们。但我确信它并不存在于他的所有代码中。我想知道。
我什么时候应该考虑使用命名参数与普通样式(func(a,b,c)
)来编写函数。某些情况(没有何时和何时不建议)
- 在同一个类中调用公共方法 在
- 同一个类中调用私有方法 在
- 外部第 3 方库中
- 调用方法 在同一命名空间中调用另一个类中的
- 方法 在不同命名空间中调用另一个类中的方法命名空间或模块
从不属于库的内部类调用方法
public bool RenameFolderIn(PK 文件夹Id,字符串新文件夹名称) { 返回RenameFolder(新文件夹名称:新文件夹名称,infolder:true,folderId:folderId); } 公共布尔RenameFolderOut(PK文件夹Id,字符串新文件夹名称) { return RenameFolder(newfoldername: newfoldername, infolder: false,folderId:folderId); } public bool RenameFolder(PK文件夹Id,字符串新文件夹名称,bool infolder) {
I was splitting RenameFolder to two pieces and i notice visual studios 2010 supports named parameters! (example below).
I know this has existed for a number of years in other languages. I remember a professor saying why he likes named parameters and that he uses them in all of his code. But i am sure its not in all of his code. I was wondering.
When should i consider to write the function using a named parameter vs normal style (func(a,b,c)
). Some cases area (without a when and when not suggestion)
- Calling public methods in the same class
- Calling private methods in the same class
- Calling methods in external 3rd party libraries
- Calling methods in another class in the same namespace
- Calling methods in another class in a different namespace or module
Calling methods from internal classes not meant to be a library
public bool RenameFolderIn(PK folderId, string newfoldername) { return RenameFolder(newfoldername: newfoldername, infolder: true, folderId: folderId); } public bool RenameFolderOut(PK folderId, string newfoldername) { return RenameFolder(newfoldername: newfoldername, infolder: false, folderId: folderId); } public bool RenameFolder(PK folderId, string newfoldername, bool infolder) {
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
通常,当有大量默认值并且我只需要指定一些非默认值,或者当函数名称没有表明参数的顺序时,我会使用命名参数。在示例
RenameFolder*
函数中,我希望文件夹位于新名称之前(RenameFolder
可以是短语“重命名文件夹文件夹 to name”;如果可能的话,将名称放在第一位,这不是明显的方法),因此不会为命名参数而烦恼。示例:假设
Gamma
是 Gamma 分布的构造函数,它有两个参数:shape 和 scale。在 scale 之前传递 shape 有一个统计约定,但该约定从名称中并不明显,因此我们使用命名参数。Typically, I use named parameters when there are a large number of default values and I only need to specify a few non-default, or when the function name doesn't suggest the order of parameters. In the example
RenameFolder*
functions, I would expect the folder to come before the new name (RenameFolder
can be short for the phrase "rename folder folder to name"; phrasing it so the name comes first, if possible, isn't the obvious approach), and so wouldn't bother with named parameters.Example: suppose
Gamma
is a constructor for the Gamma distribution, which hase two parameters: shape and scale. There's a statistical convention for passing shape before scale, but the convention isn't obvious from the name, so we use named parameters.