我在这里有一个奇怪的人。我想匹配通用参数的类型。这是我到目前为止的内容:
open System.Reflection
type Chicken = {
Size : decimal
Name : string
}
let silly<'T> x =
match type<'T> with
| typeof<Chicken> -> printfn "%A" x
| _ -> printfn "Didn't match type"
enter code here
我希望silly<'T>
函数采用通用参数,然后匹配该函数中的类型以确定输出。现在,我收到有关缩进不正确的编译器错误。我很确定缩进是可以的,但是我在做编译器时根本不喜欢它。有什么想法吗?我有一个蛮力的解决方法,但是这种方法会简单得多。
答案 0 :(得分:4)
我认为这就是您想要的:
let silly x =
match box x with
| :? Chicken as chicken -> printfn "is a chicken = %s %A" chicken.Name chicken.Size
| :? string as txt -> printfn "is a string = '%s'" txt
| :? int as n -> printfn "is an int = %d" n
| _ -> printfn "Didn't match type"
这样称呼它:
silly "Hello"
silly 7
silly { Name = "Claudius" ; Size = 10m }
// is a string = 'Hello'
// is an int = 7
// is a chicken = Claudius 10M
答案 1 :(得分:2)
这是我一直在做的事情,不确定它是否是“最好的”,但是它对我和我的团队都有效并且有意义。
let silly<'T> x =
match typeof<'T> with
| t when t = typeof<TypeA> -> TypeASpecificFunction x
| t when t = typeof<TypeB> -> TypeBSpecificFunction x
| t when t = typeof<TypeC> -> TypeCSpecificFunction x
| _ -> printfn "Didn't match type"
它需要一个通用函数,这种方法不能直接用于typeof