方法参数数组默认值 [英] Method parameter array default value
问题描述
在c#中,可以在方法中使用默认参数值,例如:
In c# it is possible to use default parameter values in a method, in example:
public void SomeMethod(String someString = "string value")
{
Debug.WriteLine(someString);
}
但是现在我想使用数组作为方法中的参数,并为其设置默认值.
我以为它应该看起来像这样:
But now I want to use an array as the parameter in the method, and set a default value for it.
I was thinking it should look something like this:
public void SomeMethod(String[] arrayString = {"value 1", "value 2", "value 3"})
{
foreach(someString in arrayString)
{
Debug.WriteLine(someString);
}
}
但这不起作用.
如果有可能的话,是否有正确的方法?
But this does not work.
Is there a correct way to do this, if this is even possible at all?
推荐答案
即使有可能,是否有正确的方法呢?
Is there a correct way to do this, if this is even possible at all?
This is not possible (directly) as the default value must be one of the following (from Optional Arguments):
- 一个常量表达式;
- 形式为new ValType()的表达式,其中ValType是值类型,例如枚举或结构;
- default(ValType)形式的表达式,其中ValType是值类型.
创建数组不适合可选参数的任何可能的默认值.
Creating an array doesn't fit any of the possible default values for optional arguments.
最好的选择是重载:
public void SomeMethod()
{
SomeMethod(new[] {"value 1", "value 2", "value 3"});
}
public void SomeMethod(String[] arrayString)
{
foreach(someString in arrayString)
{
Debug.WriteLine(someString);
}
}
这篇关于方法参数数组默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!