我有一个称为“Pane”(玻璃 Pane )的类,它实现了IPane:

type IPane =
    abstract PaneNumber : int with get, set
    abstract Thickness : float<m> with get, set
    abstract ComponentNumber : int with get, set
    abstract Spectra : IGlassDataValues with get, set
    ...

type Pane(paneNumber, componentNumber, spectra, ...) =
    let mutable p = paneNumber
    let mutable n = componentNumber
    let mutable s = spectra
    ...

    interface IPane with
        member this.PaneNumber
            with get() = p
            and set(value) = p <- value
        member this.ComponentNumber
            with get() = n
            and set(value) = n <- value
        member this.Spectra
            with get() = s
            and set(value) = s <- value
            ...

我创建一个 Pane 列表( Pane 列表):
let p = [ p1; p2 ]

但是我需要将其转换为IPane列表,因为这是另一个函数中的参数类型。以下代码会产生错误:
let p = [ p1; p2 ] :> IPane list
'Type constraint mismatch. The type
  Pane list
is not compatible with type
  IPane list
The type 'IPane' does not match the type 'Pane'

当Pane实现IPane时,这令人困惑。将Pane列表对象作为参数简单地传递到所需函数中也会产生错误。

如何将“ Pane ”列表转换为IPane列表?

最佳答案

F#不允许以您想要的方式继承。

更好的方法是使用:

[p1 ;p2] |> List.map (fun x -> x:> IPane)

另外,您可以更改功能以使用类似这样的内容
let f (t:#IPane list) = ()

在这里您可以执行f [p1;p2],因为#告诉编译器任何从IPane继承的类型都可以。

关于interface - F#将对象转换到接口(interface),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24055546/

10-15 02:36