开发者

How to check in F# whether object implements interface

Prototypical code in C#:

if(obj1 is ISomeInterface) {
   do_something
}

Code in F# that doesn't compile:

match obj1 with 
| :? ISomeInterface 开发者_C百科-> do_something
| _ -> ()


To add some explanation for the answers by desco and Brian - adding box is needed when the static type of the obj1 value may not necessariliy be a .NET reference type.

If the type of obj1 is obj (type alias for System.Object) then you can use pattern matching without any boxing, because the compiler already knows you have a reference type:

let obj1 : obj = upcast (...)
match obj1 with 
| :? ISomeInterface -> (do something)

The case where you need box is when the type of obj1 is generic type parameter. In this case, your function can be called with both value types and reference types. Adding box ensures that you're performing type test on reference type (and not on value type, which is not possible).


match box obj1 with 
| :? ISomeInterface -> do_something
| _ -> ()


While match box obj1 with ... does the job, there is a box IL instruction emitted by F# compiler. Box instruction is dangerous because it tends to be slow under some circumstances.

If you know that obj1 is already a reference type then a faster :> obj approach is recommended:

match obj1 :> obj with
    | :? ISomeInterface -> (do something)

obj1 :> obj is equivalent to C# (object)obj1 type cast operation. Moreover, F# compiler optimizes out that excessive cast operation when the project is built in Release configuration, so you get the fastest code in this case.


match box obj1 with ...

I think (typing from my phone :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜