【问题标题】:Using unit as Type Parameter and overriding methods使用单位作为类型参数和覆盖方法
【发布时间】:2012-04-04 13:26:10
【问题描述】:

我基本上是在问为什么以下代码行无法编译:

type IGenericType<'a> = 
    abstract member MyFunc : 'a -> 'a -> 'a

type Implementer() = 
    member x.Test () () = () // unit->unit->unit
    interface IGenericType<unit> with 
        member x.MyFunc a b = b // FS0017
        // member x.MyFunc () () = () // FS0017

只是好奇是否有一种方法可以使这项工作按预期进行。我认为这是一个限制,它与单元和泛型的实现有关。

我目前正在使用以下解决方法:

type Nothing = 
    | Nothing
type Implementer() = 
    interface IGenericType<Nothing> with 
        member x.MyFunc a b = b

希望有人能对这种行为有所启发。

【问题讨论】:

    标签: .net f#


    【解决方案1】:

    你猜对了。对于 .NET 框架内的互操作性,F# 编译器不会为 unit 发出 IL,而是将其替换为 void

    因此,您的通用接口适用于除unit 之外的任何类型。这似乎不是什么大问题;您的解决方法是解决此问题的好方法。

    更详细的讨论可以在F# interface inheritance failure due to unit找到。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-18
      • 1970-01-01
      • 2012-12-21
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-08
      相关资源
      最近更新 更多