Usage of named parameters

后端 未结 5 1245
情歌与酒
情歌与酒 2021-01-06 11:04

Sorry, if duplicate.

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

So, can you give some exam

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-06 11:35

    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.

    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);
    

    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.

提交回复
热议问题