【问题标题】:Initialize IEnumerable<int> as optional parameter将 IEnumerable<int> 初始化为可选参数
【发布时间】:2013-01-10 18:02:55
【问题描述】:

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

【问题讨论】:

    标签: c# ienumerable


    【解决方案1】:

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

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

    下一个代码 sn-p 取自著名的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));
    

    【讨论】:

    • 这种模式真正令人敬畏的副作用是,如果您通过某些类库公开这些默认参数,您不会遇到调用站点绑定的问题,因为这允许您修改默认值并让它们在库更新时生效。从而避免这个问题:stackoverflow.com/a/664691/84206
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

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

      numbers = numbers ?? new []{ 1, 2, 3}.AsEnumerable();
      

      【讨论】:

        【解决方案4】:

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

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

        public void Foo(int arg1)
        {
              Foo(arg1, new[] { 1, 2, 3 });
        }
        
        public void Foo(int arg1, IEnumerable<int> arg2)
        {
              // do something
        }
        

        【讨论】:

          【解决方案5】:

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

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

           list = list ?? new List<int>(){1,2,3,4};
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-08-03
            • 1970-01-01
            • 1970-01-01
            • 2021-04-05
            • 2012-11-10
            • 2016-05-02
            • 1970-01-01
            相关资源
            最近更新 更多