9

IEnumerable<int>我的C# 方法中有一个类型的可选参数。我可以用除 之外的任何东西来初始化它null,例如一个固定的值列表吗?

4

5 回答 5

13

不,你只能有编译时常量。您可以分配到 null 然后

void SomeMethod(IEnumerable<int> list = null)
{
    if(list == null)
        list = new List<int>{1,2,3};
}

下一个代码片段取自C# in Depth. Jon Skeet第 371 页。他建议使用 null 作为not set参数的一种指示符,它可能具有有意义的默认值。

static void AppendTimestamp(string filename,
                            string message,
                            Encoding encoding = null,
                            DateTime? timestamp = null)
{
     Encoding realEncoding = encoding ?? Encoding.UTF8;
     DateTime realTimestamp = timestamp ?? DateTime.Now;
     using (TextWriter writer = new StreamWriter(filename, true, realEncoding))
     {
         writer.WriteLine("{0:s}: {1}", realTimestamp, message);
     }
}

用法

AppendTimestamp("utf8.txt", "First message");
AppendTimestamp("ascii.txt", "ASCII", Encoding.ASCII);
AppendTimestamp("utf8.txt", "Message in the future", null, new DateTime(2030, 1, 1));
于 2013-01-10T09:59:11.007 回答
4

否 - 默认参数必须是编译时常量。

您最好的选择是重载该方法。或者,将默认值设置为 null 并在您的方法内部检测 null 并将其转换为您想要的列表。

于 2013-01-10T09:58:38.310 回答
4

如何将其默认值设为 null,并在方法内

numbers = numbers ?? Enumerable.Empty<int>();

或者

numbers = numbers ?? new []{ 1, 2, 3}.AsEnumerable();
于 2013-01-10T09:59:34.073 回答
3

好吧,因为您需要编译时常量,所以您必须将其设置为null

但是您可以在您的方法中执行以下操作

 list = list ?? new List<int>(){1,2,3,4};
于 2013-01-10T10:02:55.193 回答
3

不,您需要一个编译时间常数。

但是您可以使用重载作为解决方法:

public void Foo(int arg1)
{
      Foo(arg1, new[] { 1, 2, 3 });
}

public void Foo(int arg1, IEnumerable<int> arg2)
{
      // do something
}
于 2013-01-10T10:01:32.590 回答