【问题标题】:What is the correct way to call DateTime.TryParse from F#?从 F# 调用 DateTime.TryParse 的正确方法是什么?
【发布时间】:2012-11-27 17:05:09
【问题描述】:

从 F# 调用 DateTime.TryParse 的正确方法是什么?我正在尝试从 F# 交互式测试一些代码,但我不知道如何通过 ref 将可变的 DateTime 传递给第二个参数。 F# 中的 in/out/ref 语法是什么?

这是我正在查看的方法签名: http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx?cs-save-lang=1&cs-lang=fsharp#code-snippet-1

【问题讨论】:

标签: .net f# tryparse


【解决方案1】:

如果您确实需要通过引用传递可变的DateTime,那么克里斯的回答是正确的。但是,在 F# 中使用编译器将尾随 out 参数视为元组返回值的能力更为惯用:

let couldParse, parsedDate = System.DateTime.TryParse("11/27/2012")

这里,第一个值是bool返回值,而第二个是分配的out参数。

【讨论】:

  • 结果将来自以下元组:(false, DateTime.MinValue) 和 (true, DateTime(2012,11,27))
【解决方案2】:

以下是在 F# 中执行 DateTime.TryParse 的方法:

let mutable dt2 = System.DateTime.Now
let b2 = System.DateTime.TryParse("12-20-04 12:21:00", &dt2)

& 运算符在哪里找到 dt2 的内存地址以修改引用。

这里有一些关于 F# 参数语法的 additional information

【讨论】:

  • 这不是首选方式,请不要在那里使用可变 dt2
  • @Alex,OP 希望使用可变的 DateTime 作为第二个参数。我同意您可以更干净地调用 DateTime.Parse,但这不是被问到的问题。
【解决方案3】:

为了完整起见,另一种选择是使用参考单元格,例如

let d = ref System.DateTime.MinValue
if (System.DateTime.TryParse("1/1/1", d)) then
   // ...

【讨论】:

【解决方案4】:

我又找到了一种方式,看起来更实用的风格(来自https://stackoverflow.com/a/4950763/1349649

match System.DateTime.TryParse "1-1-2011" with
| true, date -> printfn "Success: %A" date
| _ -> printfn "Failed!"

不幸的是,我找不到任何关于它如何工作的信息。

【讨论】:

    【解决方案5】:

    我有一个帮助模块,我喜欢将其包含在我的所有项目中。我收集这样的东西,将所有命令式 -> 功能转换放在一个地方以供重用:

    
    module helper = 
        
        //if some, unwrap input and call fun
        let inline ( |>- ) x f  = Option.bind f x //bind f x
        //if some, unwrap input, call fun, and wrap output 
        let inline ( |>-+ ) x f = Option.map f x 
    
        module dateTime =
    
          let tryParse (input: string) : DateTime option =
            let mutable dt = DateTime.Now
            if DateTime.TryParse(input, &dt) then Some dt else None
    
    

    【讨论】:

      猜你喜欢
      • 2023-03-10
      • 1970-01-01
      • 2011-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多