2
  >     type XList<'T> (_collection : seq<'T>) =
            inherit List<'T> (_collection)
            member this.Add _item = if not <| this.Contains _item then base.Add _item
            new () = XList<'T> (Seq.empty<'T>);;

              inherit List<'T> (_collection)
      --------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

stdin(47,9): error FS0945: Cannot inherit a sealed type


我的理解是 List<'T> 实际上没有密封。不?

此外,这似乎在 F# 交互之外工作得很好。确切的代码在我的 F# 项目中,编译器会毫无怨言地处理它。我在几个 C# 项目中也发生了同样的事情。代码在每种情况下都按预期工作。

通常,我只是使用静态方法扩展 List<'T> (以“F# 方式”进行),但隐藏 List.Add 也应该可以正常工作。

4

3 回答 3

5

正如其他人已经解释的那样,您的代码实际上尝试从 F# 列表类型(已密封)继承。这有点令人困惑,但 F# 提供了一个ResizeArray<T>代表通用 .NETList<T>类型的别名,因此您也可以在不使用长名称的情况下解决这个问题:

type XList<'T> (_collection : seq<'T>) = 
  inherit ResizeArray<'T> (_collection) 
于 2011-06-10T19:44:42.113 回答
4

尝试完全限定类型名称:inherit System.Collections.Generic.List<'T> (_collection)

于 2011-06-10T18:24:20.990 回答
2

我猜您的 F# 交互具有open与您的 F# 项目代码不同的命名空间集?也就是说,这是System.Collections.Generic.List还是什么?

于 2011-06-10T18:22:54.813 回答