【发布时间】:2015-12-22 05:02:17
【问题描述】:
以下产生
这种构造导致代码比类型注释所指示的更通用。类型变量 'P 已被限制为类型 'bool'。
let myValue = 表达式的右侧,以及
此代码的通用性低于其注释所需的通用性,因为显式类型变量“P”无法通用化。它被限制为“布尔”。
对于Value 方法中的通用<'P>:
type MyTypeA<'T> (myObject : 'T) as this =
let myValue = this.Value<bool> "SomeBooleanProperty"
member this.Value<'P> name = typeof<'T>.GetProperty(name, typeof<'P>).GetValue(myObject, null) :?> 'P`
但是,这编译得很好,不会产生警告或错误:
type MyTypeB<'T> (myObject : 'T) as this =
member this.Value<'P> name = typeof<'T>.GetProperty(name, typeof<'P>).GetValue(myObject, null) :?> 'P
member this.Method<'P> name = this.Value<'P> name
这是怎么回事?为什么在第一个示例中,该方法在私有值的分配中被识别,而不是合法的泛型方法?
【问题讨论】:
-
更简单的重现 - 我认为这可能是一个错误:
> type test() as this = let x = this.Value<bool>() member this.Value<'P>() = ();;似乎编译器应该在这里泛化,但由于某种原因不是 -
@JohnPalmer 有趣的事情:只要您删除
<bool>,它就会立即生效 - 我同意这是隐藏在规范中某处的一些边界案例或错误 -
如果你让 Value 可变:
let mutable myValue : bool = false并在 Method 之后放置member this.myValue = this.Value<bool> "SomeBooleanProperty",那么它就可以工作。如果你把它放在前面,它会给出错误。这似乎是一个极端情况下的错误,因为规范中没有提到泛型。 -
澄清一下:
type MyTypeA<'T> (myObject : 'T) as this = let mutable myValue : bool = false do myValue <- this.myVal2 member this.Value<'P> name = typeof<'T>.GetProperty(name, typeof<'P>).GetValue(myObject, null) :?> 'P member this.myVal2 = this.Value<bool> "SomeBooleanProperty"有效,但type MyTypeA<'T> (myObject : 'T) as this = let mutable myValue : bool = false do myValue <- this.myVal2 member this.myVal2 = this.Value<bool> "SomeBooleanProperty" member this.Value<'P> name = typeof<'T>.GetProperty(name, typeof<'P>).GetValue(myObject, null) :?> 'P无效。
标签: f# type-inference type-constraints