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

一笑奈何 提交于 2019-11-28 12:01:52

@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."

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!