inheritance - 使用带有派生类型(F#)的参数的函数

标签 inheritance casting f# code-reuse upcasting

我的应用程序中有一个类-为简单起见,我们假设它的定义如下:

type baseType() =
    member this.A = 5.

另外,我有很多函数都将这种类型的对象作为参数。而且,其中一些采用这种类型的数组:
let myFun (xArr : baseType[]) =
    // ... do something inspirig ;)

现在我意识到,拥有另一个从“baseType”派生的类会很好。例如。:
type inhType() =
    inherit baseType()
    member this.B = 8.

但是,我不能将继承类型的数组与“myFun”之类的函数一起使用
let baseArr = [| baseType() |]
let inhArr = [| inhType() |]

myFun baseArr
myFun inhArr // won't work

这将是“很高兴”。是否有一种简单的方法可以重复使用我的功能而无需进行太多更改?

我猜解决方案之一是使用例如映射我的数组函数(fun(d:inhType)-> d:> baseType),但是我想知道是否还有其他事情可以做。

最佳答案

您需要注释您的函数为接受flexible type

type A() = class end
type B() = inherit A()

let aArr = [| A() |]
let bArr = [| B() |]

// put # before type to indicate it's a flexible type
let f (x : #A[]) = ()

f aArr
f bArr  // works!

关于inheritance - 使用带有派生类型(F#)的参数的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18243494/

相关文章:

c++ - 对可变参数模板多继承函数调用的访问不明确

java - 虽然我已经为对象属性定义了值,但是它们都变成了 null?为什么?

postgresql - 将值从以 N 为基数的字符串表示形式转换为数字

c# - 迁移到 .NET8 后,F# 查询表达式和带有 Array.Contains 的 C# LINQ 失败

types - F# 强制转换/将自定义类型转换为原始类型

java - 找不到标志。正在寻找父类(super class)而不是子类

Java从对象到子类的转换

c++ - 将 unique_ptr 的 vector 数据转换为指向 const 指针的指针

c++ - 在 C/C++ 中将 int 转换为 bool

F# kprintf : missing warning about about redundant arguments