如何传递可选参数

Dha*_*tel 6 c# optional-parameters

我有一个函数有两个固定的参数.但是下一个论点并不固定,可能有两个或三个或四个.

这是一个运行时参数,那么如何定义该函数呢?

我的代码看起来像:

public ObservableCollection<ERCErrors> ErrorCollectionWithValue
    (string ErrorDode, int MulCopyNo, dynamic arguments comming it should be 2 or 3)
        {

        return null;
    }
Run Code Online (Sandbox Code Playgroud)

hor*_*rgh 12

1)参数(C#参考)

public ObservableCollection<ERCErrors>ErrorCollectionWithValue
                (string ErrorDode, int MulCopyNo, params object[] args)
{
    //...
}
Run Code Online (Sandbox Code Playgroud)

2)命名和可选参数(C#编程指南)

public ObservableCollection<ERCErrors> ErrorCollectionWithValue
    (string ErrorDode, int MulCopyNo, object arg1 = null, int arg2 = int.MinValue)
{
    //...
}
Run Code Online (Sandbox Code Playgroud)

3)也许简单的方法重载仍然适合更好,将方法逻辑分离到不同的方法?在此链接下,您还可以找到命名参数和可选参数的其他说明


cod*_*biz 5

一种方法是重载方法

public ObservableCollection<ERCErrors> ErrorCollectionWithValue
    (string ErrorDode, int MulCopyNo, int param1)
{
   //do some thing with param1
}

public ObservableCollection<ERCErrors> ErrorCollectionWithValue
    (string ErrorDode, int MulCopyNo, int param1,int param2)
{
   //do some thing with param1 and param3
}

public ObservableCollection<ERCErrors> ErrorCollectionWithValue
    (string ErrorDode, int MulCopyNo, int param1, int param2, int param3)
    {
       //do some thing with param1, param2 and param3
    }
Run Code Online (Sandbox Code Playgroud)

那么所有这些都是有效的

var err = ErrorCollectionWithValue("text", 10, 1);
var err = ErrorCollectionWithValue("text", 10, 1,2);
var err = ErrorCollectionWithValue("text", 10, 1,2,3);
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用可选参数.有了这个,你只需要一种方法,而不是第一种方法中的3种方法.

public ObservableCollection<ERCErrors> ErrorCollectionWithValue
    (string ErrorDode, int MulCopyNo, int param1 = 0, int param2 = 0, optional int param3 = 0)
{

}
Run Code Online (Sandbox Code Playgroud)

这些仍然有效

var err = ErrorCollectionWithValue("text", 10, 1); //defaults param2 and param3 to 0
var err = ErrorCollectionWithValue("text", 10, 1,2); //defaults param3 to 0
var err = ErrorCollectionWithValue("text", 10, 1,2,3);
Run Code Online (Sandbox Code Playgroud)

要跳过任何可选参数,您需要使用命名参数,仅在C#4.0及更高版本中受支持

var err = ErrorCollectionWithValue("text", param3: 5); //skipping param1 and param2
Run Code Online (Sandbox Code Playgroud)

在另外两种方法中,您不能跳过参数的顺序.