English 中文(简体)
C#[复制]
原标题:optional array Parameter in C# [duplicate]
  • 时间:2011-11-21 14:54:32
  •  标签:
  • c#
  • c#-4.0
This question already has answers here:
Closed 11 years ago.

Possible Duplicate:
passing an empty array as default value of optional parameter in c#

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#选用参数<代码>tags,使参数成为选择,使你可以在方法签名上设定违约值。 我尝试了以下的 ha,但没有工作。

www.un.org/Depts/DGACM/index_spanish.htm 做工守则—— 1

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

www.un.org/Depts/DGACM/index_spanish.htm 做工守则—— 2

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

请说明我失踪的情况。


我已经看到这个问题:

通过空阵作为任择参数的缺省值

最佳回答

documentation 任择论点指出:

缺省值必须是以下类型的表述之一:

  • a 经常表示;

  • a 表示以下表格:new ValType(),其中ValType为一种价值类型,例如enum <>/code>或struct;

  • a 表格default(ValType)的表述,其中ValType为价值类型。

由于<代码>新载体[0]既不是一种固定的表述,也不是new 说明,其次为价值类型,因此不能用作缺省理由值。

您提出的问题中的第一部法典确实是一个好的工作:

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

不能确定,是否正在使这项工作正确。

  static void Main(string[] args)
        {
                TestMe();

        }


private static void TestMe(string[] param = null)
    {
        if (param == null)
        { 
            Console.WriteLine("its empty");
        }
    }

还必须汇编时间不变的价值。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签