What is the correct way to call DateTime.TryParse from F#?

泄露秘密 提交于 2019-11-29 05:05:08

问题


What is the correct way to call DateTime.TryParse from F#? I am trying to test some code from F# interactive and I can't figure out how to pass a mutable DateTime into the second argument by ref. What is the in/out/ref syntax in F#?

This is the method signature I'm looking at: http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx?cs-save-lang=1&cs-lang=fsharp#code-snippet-1


回答1:


Chris's answer is correct if you really need to pass a mutable DateTime by reference. However, it is much more idiomatic in F# to use the compiler's ability to treat trailing out parameters as tupled return values:

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

Here, the first value is the bool return value, while the second is the assigned out parameter.




回答2:


Here's how to execute DateTime.TryParse in F#:

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

Where the & operator finds the memory address of dt2 in order to modify the reference.

Here's some additional information on F# parameter syntaxt.




回答3:


Just for the sake of completeness, yet another option is to use ref cells, e.g.

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



回答4:


I've found one more way, it seems more functional style (from https://stackoverflow.com/a/4950763/1349649)

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

Unfirtunately, I can't find any information about how it works.



来源:https://stackoverflow.com/questions/13589311/what-is-the-correct-way-to-call-datetime-tryparse-from-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!