来自 Array Covariance文章:
Arrays where the element type is a reference type are covariant. [...] It was added to the CLR because Java requires it and the CLR designers wanted to be able to support Java-like languages.
CLR 支持数组协变,但如何在 F# 中使用这个方便的功能?
type Foo () = class end
type Bar () = inherit Foo ()
// must have type Foo []
let foo : Foo [] = Array.create 1 (Bar ())
// ^^^^^^ must not cast to Foo
// must throw ArrayTypeMismatchException
foo.[0] <- Foo ()
在示例中,我想让 foo
在后台存储一个 Bar
数组,就像在 CLR 中实现的那样。
最佳答案
在许多 C# 允许类型间隐式转换的地方,F# 需要显式转换。
F# 编译器甚至不允许从 Bar[]
直接转换为 Foo[]
('Bar[]' 类型没有任何正确的子类型,不能用作类型测试或运行时强制转换的来源。),您需要先转换为 object
。
let foo = Array.create 1 (Bar ()) :> obj :?> Foo[]
顺便说一句,我不会把数组协变称为一个方便的特性,它导致的问题多于它解决的问题。
关于c# - 如何使数组协方差在 F# 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43559998/