如何在 F# 中使用类型注释实现泛型

How to implement generics with type annotations in F#

我有以下代码框架:

type MyException<'T> () =
    inherit Exception()

type IMyInterface =
    abstract member Method<'T when 'T : (new: unit -> 'T) and 'T :> Exception> : string -> int

type MyClass =
    interface IMyInterface with
        member this.Method s =
            let i = s.IndexOf "a"
            if i = -1 then raise (new MyException<'T> ())
            i

但是,我收到以下消息:

This construct causes code to be less generic than indicated by the type annotations. The type variable 'T has been constrained to be type 'obj'.

并且在编译时,obj 被传递给 MyException 而不是 'T

我需要在IMyInterface.Method上有上面的类型约束,还需要在MyClass.Method中把传给MyException的类型传进去。我怎样才能做到这一点?

我认为你必须设置参数 MyClass:

type MyClass<'T> =
    interface IMyInterface with
        member this.Method s =
            let i = s.IndexOf "a"
            if i = -1 then raise (new MyException<'T> ())
            i

或对您的方法重复约束:

type MyClass =
    interface IMyInterface with
        member this.Method<'T when 'T : (new: unit -> 'T) and 'T :> Exception> s =
            let i = s.IndexOf "a"
            if i = -1 then raise (new MyException<'T> ())
            i