Method parameter array default value [duplicate]

北城余情 提交于 2019-11-28 07:20:48

问题


This question already has an answer here:

  • Passing an empty array as default value of an optional parameter [duplicate] 3 answers

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?


回答1:


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):

  • 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.

Creating an array doesn't fit any of the possible default values for optional arguments.

The best option here is to make an overload:

public void SomeMethod()
{
    SomeMethod(new[] {"value 1", "value 2", "value 3"});
}


public void SomeMethod(String[] arrayString)
{
    foreach(someString in arrayString)
    {
        Debug.WriteLine(someString);
    }
}



回答2:


Try this:

public void SomeMethod(String[] arrayString = null)
{
    arrayString = arrayString ?? {"value 1", "value 2", "value 3"};
    foreach(someString in arrayString)
    {
        Debug.WriteLine(someString);
    }
}
someMethod();


来源:https://stackoverflow.com/questions/12607146/method-parameter-array-default-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!