如果 Dictionary/Array/Map 存在

If Dictionary/Array/Map Exists

所以在 F# 中寻找一种方法来检查变量是否存在,如果存在,是否是字典。

用例是一个模板系统,所以会有类似 HTML 文件中的 {{dictionaryName|key}}。

如果 dictionaryName 是一个有效的字典,我只想解析它。

谢谢

在 F# 中无法使用不存在的变量(您声明这些变量,编译器将检查标识符是否为 introduced/defined)。

所以我猜您想检查它是否是 null 或者 - 如果不是 - Dictionary 的实例?

在这种情况下,您可以使用 type test pattern 匹配:

match value with
| null -> ... // what do you want the expressions value to be if null?
| :? Dictionary<string,string> as dict -> ... // you can use `dict` to compute your resulting-value
| _ -> ... // else/default - case

现在假设您知道字典的完整类型(我使用 string 作为键和值作为示例)

如果不是,您可以匹配使用反射的 IDictionary,但我会先尝试这个。


更新

在 dictionary-key/value 上进行模式匹配:

match dict.TryGetValue key with
| (true, value) -> ...
| (false, _) -> ... // Key not in dictionary