c# - 如何使数组协方差在 F# 中工作

标签 c# .net f# functional-programming clr

来自 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/

相关文章:

c# - 如何永久为所有查询请求启用 Apollo Tracing with Hot Chocolate?

.net - NuGet 用于多个项目的解决方案

.net - FsCheck 和 NUnit 集成

javascript - MVC5如何将TinyMCE值绑定(bind)到模型

c# - 如何正确使用 CharacterController.Move() 来移动角色

c# - 是否可以在 WPF 的单独进程中隔离某些控件?

f# - "do"句子中的 "do Application.Run(form)"

f# - 重载度量​​运算符 (*)

c# - MVC 5/.NET 4.5 - 长时间运行的进程

c# - jQuery AJAX JSON 引用格式到 WCF