函数值参数类型不匹配

问题描述 投票:0回答:1

以下代码会在

myFunctions.Add fn
处生成编译时错误:

type IInterface = interface end

let myFunctions = ResizeArray<IInterface -> unit> ()

let add<'T when 'T :> IInterface> (fn: 'T -> unit) = myFunctions.Add fn

错误是“

FS0001: Type mismatch. Excpeting a 'IInterface -> unit' but given a ''T -> unit'  The type 'IInterface' does not match the type ''T'

这让我感到困惑,因为我将

'T
限制为
IInterface

以下代码没有编译时错误:

type IInterface = interface end

let myStuff = ResizeArray<IInterface> ()

let add<'T when 'T :> IInterface> (item: 'T) = myStuff.Add item

...所以函数参数的某些属性与这种方法不兼容。

这个属性是什么,有没有办法让我的方法发挥作用?

f# type-constraints
1个回答
0
投票

F# 没有对象类型的隐式向上转型。 因此,编译如下:

let add<'T when 'T :> IInterface> (fn: IInterface -> unit) = myFunctions.Add fn
© www.soinside.com 2019 - 2024. All rights reserved.