Pau*_*ung 3 f# pattern-matching
哪里request是HttpRequestMessage来自System.Net.Http,我试图使用模式匹配来确定哪种方法是用来做请求.
这是一个人为的例子,它证明了我的问题:
let m = match request.Method with
| HttpMethod.Get -> "GET"
| HttpMethod.Post -> "POST"
Run Code Online (Sandbox Code Playgroud)
这导致:
分析器错误:未定义字段,构造函数或成员"Get"
为什么这不起作用,我如何使用模式匹配或更合适的技术来实现相同的目标?
正如John Palmer在评论中指出的那样,你可以像这样写:
let m =
match request.Method with
| x when x = HttpMethod.Get -> "GET"
| x when x = HttpMethod.Post -> "POST"
| _ -> ""
Run Code Online (Sandbox Code Playgroud)
但是,如果你要重复这样做,你可能会发现这有点麻烦,在这种情况下你可以为它定义一些活动模式:
let (|GET|_|) x =
if x = HttpMethod.Get
then Some x
else None
let (|POST|_|) x =
if x = HttpMethod.Post
then Some x
else None
Run Code Online (Sandbox Code Playgroud)
哪个可以让你写这个:
let m =
match request.Method with
| GET _ -> "GET"
| POST _ -> "POST"
| _ -> ""
Run Code Online (Sandbox Code Playgroud)