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

时间:2015-06-10 23:53:02

标签: 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

但是,我收到以下消息:

  

此构造导致代码不像类型注释所指示的那样通用。类型变量'T已被约束为类型'obj'。

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

我需要在IMyInterface.Method上设置上述类型约束,并且还需要传递MyException中传递给MyClass.Method的类型。我怎么能做到这一点?

1 个答案:

答案 0 :(得分:4)

我认为你必须参数化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