Optional parameters in C#
In earlier versions before C# 4.0, optional parameters were not supported. However, there are techniques to simulate them. One way is to overload the method with a different parameter list. For example:
<code class="language-c#">public void GetFooBar(int a) { // GetFooBar 的单参数实现 } public void GetFooBar(int a, int b) { // GetFooBar 的双参数实现 }</code>
This allows you to call GetFooBar with one or two arguments, depending on your needs.
However, in C# 4.0 and later, optional parameters are directly supported using the following syntax:
<code class="language-c#">public void GetFooBar(int a, int b = 0) { // GetFooBar 的可选参数实现 }</code>
In this example, if b is not provided when calling the method, it defaults to 0. You can specify any default value you want.
The above is the detailed content of How Do Optional Parameters Work in C#?. For more information, please follow other related articles on the PHP Chinese website!