gpt4 book ai didi

f# - 如何在 F# 中检查接口(interface)实现

转载 作者:行者123 更新时间:2023-12-01 23:27:23 26 4
gpt4 key购买 nike

假设我有这些类型(请原谅 C# 语法,我是 F# 的新手):

interface I { }
class A { }
class B : A, I { }

在 C# 中我可以这样做:

A a = …
bool isI = a is I;

但是,在 F# 中,有这个:

let a : A = ...

我知道 a 可能包含 B 的实例并实现 I。然而,这会导致编译错误,提示 A is not compatible with I:

let isI = a :? I

但是,这是可行的:

let isI = a :> obj :? I

怎么会? 一个:? I 既不是悲观者也不是悲观者,这是肯定的。但是它如何与 obj 一起工作?接口(interface)是否以某种方式算作对象子类?

最佳答案

我认为the docs 中暗示了答案:

Returns true if the value matches the specified type (including if it is a subtype); otherwise, returns false (type test operator).

如果你引用the spec7.9 动态类型测试模式中,它确认这是一个编译时约束:

An error occurs if type cannot be statically determined to be a subtype of the type of the pattern input

接口(interface)在层次结构中“更高”,它不是AA 的子类型。

在 mucn 中以同样的方式,这也不会编译:

let isObj = a :? obj

首先向上转换为obj,然后您可以检查类型是否为I,因为这是obj 的子类型。

关于f# - 如何在 F# 中检查接口(interface)实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54766970/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com