我们如何在C#.net中声明可选参数?

Sai*_*ala 12 c# optional

我正在使用一种方法来执行某些操作,我希望通过在C#中使用可选参数只能编写一次方法,除了方法重载之外还有吗?

Ric*_*end 35

Visual Studio 2010新手

命名和可选参数

例如

public void ExampleMethod(int required, string optionalstr = "default string",
int optionalint = 10)
{
}
Run Code Online (Sandbox Code Playgroud)

  • FWIW,不,他没有.如果你阅读了他提供的链接,那就是MSDN给出的例子. (7认同)

小智 12

看看下面的代码

要使用的库

using System.Runtime.InteropServices;
Run Code Online (Sandbox Code Playgroud)

功能声明

private void SampleFunction([Optional]string optionalVar, string strVar)
{
}
Run Code Online (Sandbox Code Playgroud)

在给功能打电话的同时你也可以这样做

SampleFunction(optionalVar: "someValue","otherValue");
Run Code Online (Sandbox Code Playgroud)

要么

SampleFunction("otherValue");
Run Code Online (Sandbox Code Playgroud)

如果有帮助请回复.!:)


Ode*_*ded 8

是的,使用可选参数(在C#4中引入).

public void ExampleMethod(int required, string optionalstr = "default string",
    int optionalint = 10)
Run Code Online (Sandbox Code Playgroud)

为形式参数提供默认值时,它将成为可选参数.

对于以前的版本,过载是唯一的选择.