我正在使用C#创建的库。我一直在努力将一些代码移植到F#,但必须使用C#lib中的一些底层类型。
一段代码需要计算值列表并将其分配给类中的公共字段/属性。该字段是一个C#类,包含两个ICollection。
我的F#代码工作正常,需要返回F#Seq / List。
我尝试了以下代码片段,每个代码片段都会产生错误。
类中的公共字段,它是一个包含两个ICollection对象的类本身
this.field.Collection1 = recoveries
这给出了错误Expected具有类型ICollection但具有类型Recoveries list
this.field.Collection1 = new ResizeArray<Recoveries>()
给出错误预期类型ICollection,但是ResizeArray
this.field.Collection1 = new System.Collections.Generic.List<Recoveries>()
与上述相同的错误 - 预期ICollection但类型为List
有什么想法吗?从C#的角度来看,这些操作似乎是有效的,而List / ResizeArray实现了ICollection所以...我很困惑如何分配值。
我可以更改底层C#库的类型,但这可能会产生其他影响。
由于
答案 0 :(得分:6)
F#不像C#那样进行隐式转换。因此,即使System.Collections.Generic.List<'T>
实现了ICollection
接口,也不能直接将某些ICollection
类型的属性设置为System.Collections.Generic.List<'T>
的实例。< / p>
虽然修复很简单 - 您需要做的就是在分配之前向ICollection
或ResizeArray<'T>
添加System.Collections.Generic.List<'T>
的明确向上广告:
// Make sure to add an 'open' declaration for System.Collections.Generic
this.field.Collection1 = (recoveries :> ICollection)
或
this.field.Collection1 = (ResizeArray<Recoveries>() :> ICollection)