在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# specification,这是一些重要的地方:
14.2.2 Item-Qualified Lookup
[If the application expression begins with:]
<types>
expr, then use<types>
as the type arguments andexpr
as the expression argument.- expr, then use expr as the expression argument.
- otherwise use no expression argument or type arguments.
- If the [method] is labelled with the
RequiresExplicitTypeArguments
attribute then explicit type arguments must have been given.
如果指定类型实参和实参,则第一种情况适用,但是如您所见,规范也需要一些实际实参。不过,我不太确定这背后的动机是什么。
无论如何,如果您在成员的类型签名中的任何地方使用type参数,则可以使用如下类型的注释来指定它:
type Foo() =
member this.Bar<´T> (arg0:string) : ´T =
Unchecked.defaultof<´T>
let f = new Foo()
"string" |> (f.Bar : _ -> Int32)
另一方面,如果您没有在签名中的任何地方使用type参数,那么我不确定为什么首先需要它。如果仅在某些运行时处理中需要它,则可以将运行时类型表示形式作为参数:
type Foo() =
member this.Bar (t:Type) (arg0:string) = ()
let f = new Foo()
"string" |> f.Bar typeof<Int32>
关于generics - F#编译错误: Unexpected type application,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2743051/