c#设置默认参数,字符串数组(string[])

本文关键字:string 数组 字符串 设置 默认 参数 | 更新日期: 2023-09-27 18:12:07

我在谷歌上搜索了一些c#默认字符串参数的例子,发现是这样的。

string Exceptions = "John"

我需要为字符串[]设置默认值,但我还没有找到如何将字符串数组设置为c#方法的默认值。

static int startapp(string Source, string Destination, string[] Exceptions = { "John", "Paul", "Mary" })
            {
                 //do something
            }

c#设置默认参数,字符串数组(string[])

对不起,这必须是一个评论,但我没有足够的声誉来添加评论。你要找的可能就是这个答案

c#可选数组参数[duplicate]

它说(来自文档)

A default value must be one of the following types of expressions:
    a constant expression;
    an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;
    an expression of the form default(ValType), where ValType is a value type.

From MSDN

默认值必须是下列表达式类型之一:
-常量表达式;
- new ValType()形式的表达式,其中ValType是一个值类型,例如枚举或结构体;
-一个形式为default(ValType)的表达式,其中ValType是一个值类型。

在您的示例中,string[]是一个引用类型。
对于引用类型,默认值始终是null

当您尝试将新数组初始化为默认类型时,Visual Studio证明了一个解释:

默认参数值必须是编译时常数