方法参数数组默认值 [英] Method parameter array default value

查看:79
本文介绍了方法参数数组默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆