代码之家  ›  专栏  ›  技术社区  ›  Jason Whitehorn

你能用什么不同的方式写这个[关闭]

  •  2
  • Jason Whitehorn  · 技术社区  · 16 年前

    在.NET 3.5/C 3.0中有一些非常酷和令人兴奋的功能,并且有了这些功能,就有了一些非常有趣的方法来编写完全相同的代码行。

    使用上面提到的工具集(以及扩展名.NET 2.0的东西),可以合理地重写下面的代码片段的不同方式是什么?

            string uploadDirectory = "c:\\some\\path\\";
            if (Directory.Exists(uploadDirectory)) {
                string[] files = Directory.GetFiles(uploadDirectory);
                foreach (string filename in files) {
                    if (File.GetLastWriteTime(filename).AddHours(12) < DateTime.Now) {
                        File.Delete(filename);
                    }
                }
            }
    
    2 回复  |  直到 12 年前
        1
  •  9
  •   Mark Brackett    16 年前

    Lambda:

    if (Directory.Exists(uploadDirectory)) 
      Directory.GetFiles(uploadDirectory)
        .Where(f => File.GetLastWriteTime(file) < DateTime.Now.AddHours(-12))
        .Each(f => File.Delete(f));
    

    编辑:第二种想法是,通过使用directoryinfo和fileinfo而不是静态文件方法,可以避免对每个文件访问进行安全查找:

    var di = new DirectoryInfo(uploadDirectory);
    if (di.Exists()) {
       di.GetFiles()
         .Where(f => f.LastWriteTime < DateTime.Now.AddHours(-12))
         .Each(f=> f.Delete());
    }
    

    对于那些缺少自己的方法的人:

    void Each<T>(this IEnumerable e, Action<T> action) {
      foreach (T t in e) {
        action(t);
      }
    }
    

    为了让这真的疯狂,并符合C 3.0主题,让我们加入一个匿名类型:

    di.GetFiles().Select(f => new() {
       Delete = f.LastWriteTime < DateTime.Now.AddHours(-12) ? f.Delete : () => { }
    }).Delete();
    

    但这没有任何意义。;)

        2
  •  3
  •   Marc Gravell    16 年前

    好吧,第一个位相当整齐地映射到一个LINQ查询…但在常规的直线运动中(故意地)没有前臂。不过,我们可以惹恼Eric并添加一个;-p

    所以下面使用了linq和自定义扩展方法-但是我们可以重新编写 准确的 相同的代码(即相同的IL)与:

    • 查询语法(如下)
    • Fluent语法(.where().select()ec)
    • 显式静态(可枚举。其中(…)
    • lambdas vs anonymous methods vs named methods(last changes the il)
    • 带有/不带缩写(C 2.0)的委托委托“new”语法
    • 带/不带泛型类型推理的泛型调用(where()与where<t>())
    • 调用file.delete与调用x=>file.delete(x)等

    static void Main()
    {
        string uploadDirectory = "c:\\some\\path\\";
        if (Directory.Exists(uploadDirectory))
        {
            var files = from filename in Directory.GetFiles(uploadDirectory)
                      where File.GetLastWriteTime(filename) < DateTime.Now.AddHours(-12)
                      select filename;
            files.ForEach(File.Delete);            
        }
    }
    static void ForEach<T>(this IEnumerable<T> items, Action<T> action)
    {
        foreach (T item in items)
        {
            action(item);
        }
    }
    

    我们可以写 DateTime 使用自定义代码 Expression 但那太过分了…

    然而,我怀疑我们是否会用尽写作的方法;-p