具有特定类型和属性的枚举

时间:2017-10-02 23:08:14

标签: f# pattern-matching

我想验证动物是否为人,其名称为Alex。

人物对象:

type Person(name: string) =
        member this.Name = name

Enumration:

type Animal =
| Person of Person
| Cat
| Dog

模式匹配:

let KnowAnimal animal =
    match animal with
    | Person person && person.Name = "Alex" -> 1
    | Cat -> 2
    | Dog -> 3
    | _ -> 4

1 个答案:

答案 0 :(得分:3)

您可以使用when指定图案防护:

let KnowAnimal animal =
    match animal with
    | Person person when person.Name = "Alex" -> 1
    | Cat -> 2
    | Dog -> 3
    | _ -> 4