F# equivalent of `is` keyword in C#?

2019-01-19 12:04发布

My first F# day. If I have this:

let cat = Animal()

Now how do I check at later stage if cat is Animal?

In C#

bool b = cat is Animal;

In F#?

标签: types f# keyword
3条回答
女痞
2楼-- · 2019-01-19 12:18

For demonstration only (don't define an is function):

let is<'T> (x: obj) = x :? 'T

type Animal() = class end
type Cat() = inherit Animal()

let cat = Cat()
cat |> is<Animal> //true
查看更多
倾城 Initia
3楼-- · 2019-01-19 12:19

@ildjarn deserves the credit here for answering first, but I'm submitting the answer here so it can be accepted.

The F# equivalent of the C# is keyword is :?. For example:

let cat = Animal()
if cat :? Animal then
    printfn "cat is an animal."
else
    printfn "cat is not an animal."
查看更多
forever°为你锁心
4楼-- · 2019-01-19 12:31

I know I'm late. If you try to test the type of a collection in fsi with :? it will give an error, if the item types do not match. E.g.

let squares = seq { for x in 1 .. 15 -> x * x }  
squares :? list<int> ;;   // will give false  
squares :? list<string> ;; // error FS0193: Type constraint mismatch

Wrapping in a function like Daniels is<'T> works.

查看更多
登录 后发表回答