我该怎么做才能改进这个F#代码?

use*_*480 2 .net f#

我正在学习F#,所以我提出了一小段代码来帮助我掌握语言.我创建了下面的代码,从C#调用,然后保存上传的文件.我该如何改进这段代码?欢迎所有观点.

open System.Web
open System.IO

type SaveUpload(file: HttpPostedFileBase, path : string) = 

    // get the file name
    let origFileName = file.FileName

    // create the path including filename
    let filePath = Path.Combine(path, origFileName)

    // directory check
    let directory = Directory.Exists(path)

    // create directory
    let createDir x = 
        match x with
        |false -> Directory.CreateDirectory(path) |> ignore
        |true -> ()

    // save file
    let saveFile = 
        createDir directory
        if directory 
        then file.SaveAs(filePath)
Run Code Online (Sandbox Code Playgroud)

Tom*_*cek 6

以下是一些快速的想法:

  • 在你编写它时,代码是定义一个类型SaveUpload,但你实际上是在实现一些工作的代码 - 所以我不明白为什么这将是一个类型.你可以把它写成静态成员或函数(两者都看起来像C#的静态方法)

  • 我不确定Booleans使用的模式匹配在match这里是否真的有用.使用它可能更短if(但在更高级的情况下,模式匹配很好)

  • 最后,您正在定义一个变量saveFile,但这只是一个类型的值unit- 所有代码都已执行,并且当有人调用构造函数时保存文件.如果您打算将其作为方法,则需要将单位值()作为参数.

  • 类似地,directory是一个只计算一次的值 - 因此如果目录不存在,您的代码会创建它,但不会保存文件,因为该directory值仍然存在false.

所以,如果我想把它写成模块中的一个函数,我会用这样的东西:

open System.Web
open System.IO

module FileHelpers = 
  let SaveUpload (file:HttpPostedFileBase) (path:string) = 

    // get the file name
    let origFileName = file.FileName

    // create the path including filename
    let filePath = Path.Combine(path, origFileName)

    // directory check
    let pathExists () = Directory.Exists(path)

    // create directory
    let createDir () = 
        if not (pathExists ()) then
            Directory.CreateDirectory(path) |> ignore

    // save file
    createDir ()
    if pathExists() then
        file.SaveAs(filePath)
Run Code Online (Sandbox Code Playgroud)