nic*_*las 11 f# design-patterns if-statement match
第一场比赛有效,但不是第二场比赛.除了使用if/elif链之外,有没有办法在不声明变量的情况下进行匹配?
(注意我使用值elem,而我匹配变量t)
let t = typeof<string>
match propType with
| t -> elem.GetValueAsString() :> obj
| typeof<string> -> elem.GetValueAsString() :> obj
Run Code Online (Sandbox Code Playgroud)
pad*_*pad 13
你的第一个模式实际上并不匹配typeof<string>
.它绑定propType
了一个新值,它t
隐藏了前t
一个等于的值typeof<string>
.
由于typeof<string>
不是文字,第二种模式也不起作用(尽管在您的示例中它是一个冗余模式).你必须使用when
如下守卫:
match propType with
| t when t = typeof<string> -> elem.GetValueAsString() :> obj
| t -> elem.GetValueAsString() :> obj
Run Code Online (Sandbox Code Playgroud)
如果您尝试匹配值的类型,可以使用:?操作者
示例:
let testMatch (toMatch:obj) = match toMatch with
| :? string as s -> s.Split([|';'|]).[0]
| :? int as i -> (i+1).ToString()
| _ -> String.Empty
Run Code Online (Sandbox Code Playgroud)