试图理解推断的类型约束

Mil*_*oDC 6 f# type-inference type-constraints

以下产量

此构造使代码不如类型注释所指示的那样通用.类型变量'P已被约束为类型'bool'.

对于let myValue =表达的右侧,和

此代码的通用性低于其注释所需的代码,因为显式类型变量"P"无法进行泛化.它被限制为'bool'.

对于通用<'P>Value方法:

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`
Run Code Online (Sandbox Code Playgroud)

但是,这编译得很好,不会产生任何警告或错误:

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
Run Code Online (Sandbox Code Playgroud)

这里发生了什么?在第一个示例中,为什么在私有值的赋值中识别的方法,而不是合法的通用方法?

FZe*_*Zed 2

该警告是通过从ConstraintSolver.fs(FS0064)调用SolveTyparEqualsTyp fun内的CheckWarnIfRigid函数引发的。发出警告后,SolveTyparEqualsTyp将继续(因为到目前为止没有错误)求解类型约束。SolveTyparEqualsTyp的评论是:

/// Add the constraint "ty1 = ty" to the constraint problem, where ty1 is a type variable. 
/// Propagate all effects of adding this constraint, e.g. to solve other variables 
Run Code Online (Sandbox Code Playgroud)

这会导致ValueOP 示例中的成员定义出现错误 FS0663。随后出现错误 FS0660。由于某种我忽略的原因,发生了一些传播。

也许类型推断执行得太激进了。@jpe 和OP问题下面的其他评论包含更多有趣的线索。