命名参数的用法 [英] Usage of named parameters

查看:117
本文介绍了命名参数的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果重复。

我正在通过C#读取CLR。 参数章节以可选和命名参数的解释开始。

I'm reading CLR via C#. Chapter "Parameters" starts with the explanation of optional and named parameters.

因此,你可以给出一些使用命名参数有一些好处的例子,问题的风格或习惯?你个人使用命名参数吗?

So, can you give some example where using of named parameters has some benefits, or is it just the matter of style or habit? Do you personally use named parameters?

推荐答案

当与C#4中的可选参数组合时,命名参数非常有用。避免提供大量的方法重载,而是只有一个方法。

Named parameters are very useful when combined with optional parameters in C# 4. This allows you to avoid providing a lot of method overloads, and instead just have a single one.

例如,不是有一个方法的5个版本,可选参数,然后调用它:

For example, instead of having 5 versions of a method, you can provide one method with multiple optional parameters, then call it as:

this.Foo("required argument", bar: 42);

这可以简化API(一种方法,而不是多种方法),并且仍然提供相同的灵活性,要求用户键入每个参数。没有这个,你需要许多重载,或者必须提供所有的默认值。

This can simplify an API (one method instead of many), and still provide the same flexibility, without requiring the user to type in every argument. Without this, you'd either need many overloads, or have to provide all of the default values.

这篇关于命名参数的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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