在F#中,给定以下类:

type Foo() =
    member this.Bar<'t> (arg0:string) = ignore()

为什么以下编译:

let f = new Foo()
f.Bar<Int32> "string"

虽然以下内容不会编译:

let f = new Foo()
"string" |> f.Bar<Int32> //The compiler returns the error: "Unexpected type application"
有帮助吗?

解决方案

看起来不支持将方法视为第一类值时提供类型参数。我检查了 F#规范 这里有一些重要的位:

14.2.2项目资格查找
如果应用程序表达式开头:

  • <types> Expr, ,然后使用 <types> 作为类型参数和 expr 作为表达参数。
  • Expr, ,然后将expr用作表达参数。
  • 否则不使用表达参数或类型参数。
  • 如果[方法]标记 RequiresExplicitTypeArguments 属性必须给出显式类型参数。

如果指定类型的参数和参数,则适用第一种情况,但是如您所见,规范也需要一些实际参数。不过,我不太确定这是什么动机。

无论如何,如果您在成员的类型签名中使用类型参数,则可以使用这样的类型注释来指定它:

type Foo() = 
  member this.Bar<´T> (arg0:string) : ´T = 
    Unchecked.defaultof<´T>

let f = new Foo()
"string" |> (f.Bar : _ -> Int32)

另一方面,如果您不在签名中的任何地方使用类型参数,那么我不太确定为什么您首先需要它。如果仅需进行一些运行时处理,则可以将运行时类型表示作为参数:

type Foo() = 
  member this.Bar (t:Type) (arg0:string) = ()

let f = new Foo() 
"string" |> f.Bar typeof<Int32>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top