第一场比赛有效,但不是第二场比赛。 除了使用if / elif?
链之外,有没有办法在不声明变量的情况下进行匹配(注意我使用值elem,而我匹配变量t)
let t = typeof<string>
match propType with
| t -> elem.GetValueAsString() :> obj
| typeof<string> -> elem.GetValueAsString() :> obj
答案 0 :(得分: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
答案 1 :(得分:6)
如果您尝试匹配值的类型,可以使用:?操作
示例:
let testMatch (toMatch:obj) = match toMatch with
| :? string as s -> s.Split([|';'|]).[0]
| :? int as i -> (i+1).ToString()
| _ -> String.Empty