C# - 是否可以使用空参数?

时间:2011-07-05 14:15:31

标签: c# parameters params

public void Foo(params string[] values)
{
}

values可能是null,还是总是设置0个或更多项?

4 个答案:

答案 0 :(得分:64)

绝对 - 您可以使用类型为string []的参数调用它,其值为null:

string[] array = null;
Foo(array);

答案 1 :(得分:33)

我决定编写一些代码来自己测试一下。使用以下程序:

using System;

namespace TestParams
{
    class Program
    {
        static void TestParamsStrings(params string[] strings)
        {
            if(strings == null)
            {
                Console.WriteLine("strings is null.");
            }
            else
            {
                Console.WriteLine("strings is not null.");
            }
        }

        static void TestParamsInts(params int[] ints)
        {
            if (ints == null)
            {
                Console.WriteLine("ints is null.");
            }
            else
            {
                Console.WriteLine("ints is not null.");
            } 
        }

        static void Main(string[] args)
        {
            string[] stringArray = null;

            TestParamsStrings(stringArray);
            TestParamsStrings();
            TestParamsStrings(null);
            TestParamsStrings(null, null);

            Console.WriteLine("-------");

            int[] intArray = null;

            TestParamsInts(intArray);
            TestParamsInts();
            TestParamsInts(null);
            //TestParamsInts(null, null); -- Does not compile.
        }
    }
}

产生以下结果:

strings is null.
strings is not null.
strings is null.
strings is not null.
-------
ints is null.
ints is not null.
ints is null.

所以是的,与params相关的数组完全可能为null。

答案 2 :(得分:4)

我的第一个猜测是声明参数的默认值为null,这在某些情况下是有意义的,但c#语言不允许这样做。

static void Test(params object[] values = null) // does not compile
{
}
  
    

错误CS1751:无法为参数数组指定默认值

  

通过显式传递null来解决此限制的方法已经得到解决。

答案 3 :(得分:3)

除了Jon的回答,你也可以这样:

string[] array1 = new string[]; //array is not null, but empty
Foo(array1);
string[] array2 = new string[] {null, null}; //array has two items: 2 null strings
Foo(array2);