2012-03-09 42 views
11

第一个匹配有效,但不是第二个匹配。 除了使用if/elif链之外,是否有任何方法可以在不声明变量的情况下进行匹配?匹配fsharp中的typeof

(请注意,我用的是价值ELEM,而我匹配变量t)

let t = typeof<string> 
    match propType with 
    | t    -> elem.GetValueAsString() :> obj 
    | typeof<string> -> elem.GetValueAsString() :> obj 
+0

是你想根据底层对象的类型匹配还是你只是疑惑的结果呢? – 2012-03-09 15:12:19

+0

不,我有类型,我的类型变量的基础类型将始终是类型。确实是 – nicolas 2012-03-09 16:22:14

回答

12

你的第一个模式实际上不匹配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 
+0

。新手陷阱。我将重新rtfm关于匹配... – nicolas 2012-03-09 10:46:35

6

如果你想对阵的值的类型,你可以使用?运营商

例子:

let testMatch (toMatch:obj) = match toMatch with 
         | :? string as s -> s.Split([|';'|]).[0] 
         | :? int as i -> (i+1).ToString() 
         | _ -> String.Empty 
+2

在我的情况toMatch是类型本身。所以只有卫兵工作afaik。 – nicolas 2012-03-09 16:21:10

+0

好的,没关系;) – 2012-03-09 19:11:13

+1

这不是这个问题的答案,但它是我的问题。 :) – 2017-07-08 12:40:51