繁体   English   中英

F#:无法从 F# 交互中的 List<'T> 继承

[英]F#: Unable to inherit from List<'T> in F# interactive

  >     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# 项目中也发生了同样的事情。 代码在每种情况下都按预期工作。

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

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

type XList<'T> (_collection : seq<'T>) = 
  inherit ResizeArray<'T> (_collection) 

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM