c# - 如何传递可选参数

标签 c# optional-parameters

我有一个函数有两个固定参数。但是下一个参数不是固定的,可以有两个或三个或四个。

这是一个运行时参数,所以我该如何定义该函数?

我的代码如下:

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

        return null;
    }

最佳答案

1) params (C# Reference)

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

2) Named and Optional Arguments (C# Programming Guide)

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

3) 也许是简单的方法 overloading将方法逻辑分离到不同的方法仍然会更好吗?在此链接下,您还可以找到命名参数和可选参数的另一说明

关于c# - 如何传递可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12577730/

相关文章:

c - MSVC : "too few arguments in function call" when omitting optional parameter

c++ - 在模板函数中使用 boost::optional arguments 作为参数

用于多个参数的 Java 可变参数

c# - 为什么 null 条件运算符对 == 和 .Equals() 的行为不同?

c# - 使用命令筛选器在 Visual Studio 扩展中随机崩溃

c# - 使用 BlobContainerClient.UploadBlobAsync() 设置内容类型

c# - 如何将项目添加到 LINQ 检索的列表

c# - DTO。属性或字段?

python - random.shuffle 随机性

c# - 如何跳过 C# 中的可选参数?