문제
I've been googling for a while now... Ok, I'm sorry, this one is pathetically easy but is there an operator in F# to compare class types, like the 'is' keyword in C#? I don't want to use a full blown match statement or start casting things. Cheers
해결책
You can use the :?
construct both as a pattern (inside match
) or as an operator:
let foo = bar :? System.Random
This behaves slightly differently than in C#, because the compiler still tries to do some checks at compile-time. For example, it is an error to use this if the result would be surely false
:
let bar = 42
let foo = bar :? System.Random // Error
I don't think this could lead to confusion, but you can always add box
to convert the argument to obj
, which can be tested against any type:
let foo = box bar :? System.Random
다른 팁
If you want a general C#-to-F# quick-reference, see
which answers this question and many others.