Подтвердить что ты не робот

С# - Возможно ли иметь нулевые параметры?

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

Возможно ли, что values может быть null или всегда будет установлено с помощью 0 или более пунктов?

4b9b3361

Ответ 1

Абсолютно - вы можете называть его аргументом типа string [] со значением null:

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

Ответ 2

Я решил написать код, чтобы проверить это для себя. Используя следующую программу:

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.

Так что да, вполне возможно, что массив, связанный с параметрами, будет null.

Ответ 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);

Ответ 4

Мое первое предположение заключалось в объявлении параметра со значением по умолчанию null, что имеет смысл в некоторых случаях, но язык С# не позволяет этого.

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

ошибка CS1751: не удается указать значение по умолчанию для массива параметров

Ответ на вопрос об этом ограничении, явно передав null, уже был дан.