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

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

问题描述

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

这里最好的选择是进行重载:

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);
    }
}

这篇关于方法参数数组默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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