F#中如何检查对象是否实现接口
C# 中的原型代码:
if(obj1 is ISomeInterface) {
do_something
}
无法编译的 F# 代码:
match obj1 with
| :? ISomeInterface -> do_something
| _ -> ()
Prototypical code in C#:
if(obj1 is ISomeInterface) {
do_something
}
Code in F# that doesn't compile:
match obj1 with
| :? ISomeInterface -> do_something
| _ -> ()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要为 desco 和 Brian 的答案添加一些解释 - 当
obj1
值的静态类型可能不一定是 .NET 引用类型时,需要添加box
。如果
obj1
的类型是obj
(System.Object
的类型别名),那么您可以使用模式匹配而无需任何装箱,因为编译器已经知道您有一个引用类型:您需要
box
的情况是当obj1
的类型是泛型类型参数时。在这种情况下,可以使用值类型和引用类型调用您的函数。添加box
可确保您对引用类型执行类型测试(而不是对值类型执行类型测试,这是不可能的)。To add some explanation for the answers by desco and Brian - adding
box
is needed when the static type of theobj1
value may not necessariliy be a .NET reference type.If the type of
obj1
isobj
(type alias forSystem.Object
) then you can use pattern matching without any boxing, because the compiler already knows you have a reference type:The case where you need
box
is when the type ofobj1
is generic type parameter. In this case, your function can be called with both value types and reference types. Addingbox
ensures that you're performing type test on reference type (and not on value type, which is not possible).虽然
match box obj1 with ...
可以完成这项工作,但 F# 编译器会发出一条box
IL 指令。盒子指令很危险,因为在某些情况下它往往很慢。如果您知道 obj1 已经是引用类型,那么更快的
:>推荐使用 obj
方法:obj1 :> obj
相当于 C#(object)obj1
类型转换操作。此外,当项目以发布配置构建时,F# 编译器会优化过多的转换操作,因此在这种情况下您可以获得最快的代码。While
match box obj1 with ...
does the job, there is abox
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: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.我想(用手机打字:)
I think (typing from my phone :)