3

我正在使用用 C# 创建的库。我一直致力于将一些代码移植到 F#,但必须使用 C# 库中的许多基础类型。

一段代码需要计算一个值列表并将其分配给类中的公共字段/属性。该字段是一个包含两个 ICollection 的 C# 类。

我的 F# 代码工作正常,需要返回一个 F# Seq/List。

我尝试了以下每个都会产生错误的代码片段。

  • F# 成员的返回类型是一个名为 recoveryList 的类型,类型为 Recoveries list
  • 类中的公共字段,该类本身包含两个 ICollection 对象

    this.field.Collection1 = recoveries
    

这给出了错误 Expected to have type ICollection but has type 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# 库的类型,但这可能有其他含义。

谢谢

4

1 回答 1

7

F# 不像 C# 那样进行隐式转换。所以即使System.Collections.Generic.List<'T>实现了ICollection接口,你也不能直接将一些ICollection-typed 属性设置为System.Collections.Generic.List<'T>.

不过,修复很简单——您需要做的就是在分配之前添加一个明确的向上转换ICollectionResizeArray<'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)
于 2013-02-16T17:13:14.333 回答