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

cm0*_*007 0 generics 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
Run Code Online (Sandbox Code Playgroud)

但是,我收到以下消息:

这种构造导致代码不像类型注释所指示的那样通用。类型变量“T”已被限制为“obj”类型。

编译时,obj传递给 MyException 而不是'T.

我需要对 进行上述类型约束IMyInterface.Method,并且还需要将传入的类型传递给MyExceptionin MyClass.Method。我怎样才能做到这一点?

Pet*_*etr 5

我认为你必须参数化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
Run Code Online (Sandbox Code Playgroud)

或重复对您的方法的限制:

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