【问题标题】:Returning multiple lists in C#在 C# 中返回多个列表
【发布时间】:2011-05-10 03:33:32
【问题描述】:

我正在使用自定义类来存储有关在基于正则表达式的目录中找到的文件的信息,并且我需要从方法中返回这些文件列表。以下是它当前工作方式的一些伪代码:

class FileList {
//propertes of the file here, such as regex name, source folder and whether it needs to be deleted after copying
}

..
..

foreach (file in directory that matches regex)
{
    new filelist
    //Set all the properties
}

return allfilelists;

但是如何返回所有列表,或者有更好的方法吗?

谢谢

【问题讨论】:

    标签: c# oop list


    【解决方案1】:

    为什么不返回一个 FileLists 列表?

    var allfilelists = new List<FileList >();
    foreach (file in directory that matches regex)
    {
        new filelist
        //Set all the properties
        allfilelists.Add(fileList);
    }
    

    【讨论】:

      【解决方案2】:

      有什么理由不返回List&lt;FileList&gt; 或类似的东西? (这里有一个抽象的选择——你可以声明该方法返回IEnumerable&lt;FileList&gt;IList&lt;FileList&gt;List&lt;FileList&gt;等)

      【讨论】:

      • ... 一个显着的区别是IEnumerable&lt;FileList&gt; 会传达该列表是只读的,并且可能尚未完全在内存中(“惰性”)。 +1
      【解决方案3】:

      或者,您可以在方法上返回 IEnumerable&lt;FileList&gt; 并使用 yield 关键字来使用延迟执行并消除 List 对象的开销(尽可能少)。

      【讨论】:

        【解决方案4】:

        您可以使用List&lt;FileList&gt;FileList[]

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-09-14
          • 1970-01-01
          • 1970-01-01
          • 2014-05-24
          • 1970-01-01
          • 1970-01-01
          • 2013-10-28
          • 1970-01-01
          相关资源
          最近更新 更多