C#中的可选数组参数 [英] optional array Parameter in C#

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

问题描述


可能重复:

传递空数组作为c#中可选参数的默认值

我有一种如下所示的方法。当前,参数 tags 不是可选的

I have a method that looks like below. Currently, the parameter tags is NOT optional

void MyMethod(string[] tags=null)
{
   tags= tags ?? new string[0];
   /*More codes*/
}

我想设置参数<根据 c#的code> tags 可选,要使参数为可选,可以在方法签名中设置默认值。我尝试了以下技巧,但没有一个起作用。

I want to make parameter tags optional, as per c# , to make a parameter optional you can set a default value in method signature. I tried the following hacks but none worked.

无效的代码-1

void MyMethod(string[] tags=new string[0]){}

无效的代码-2

void MyMethod(string[] tags={}){}

请提示我所缺少的内容。

Please suggest what I am missing.

我已经看到了这个问题:

I have already seen this question:

将空数组作为可选参数的默认值传递

推荐答案

文档对于可选参数说:


默认值必须是以下表达式之一:

A default value must be one of the following types of expressions:


  • 一个常量表达式;

  • a constant expression;

<$ c形式的表达式$ c> new ValType(),其中 ValType 是值类型,例如枚举 struct ;

an expression of the form new ValType(), where ValType is a value type, such as an enum or a struct;

default形式的表达式ValType),其中 ValType 是值类型。

由于 new string [0] 既不是常量表达式也不是 new 语句后跟值类型,不能将其用作默认参数值。

Since new string[0] is neither a constant expression nor a new statement followed by a value type, it cannot be used as a default argument value.

问题中的第一个代码摘录确实是一个不错的解决方法:

The first code excerpt in your question is indeed a good workaround:

void MyMethod(string[] tags = null)
{
   tags = tags ?? new string[0];
   // Now do something with 'tags'...
}

这篇关于C#中的可选数组参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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