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

Generics 如何在F中使用类型注释实现泛型#,generics,f#,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

我有以下代码框架:

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
键入MyException())
我
然而,我得到了以下信息:

此构造导致代码不像类型注释所指示的那样通用。类型变量“T”已被约束为类型“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
键入MyClass())
我
或者对方法重复约束:

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
类型MyClass=
接口imy接口
成员。方法'T)和'T:>Exception>s=
设i=s.IndexOf“a”

如果i=-1,则raise(新的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
键入MyClass())
我
或者对方法重复约束:

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
类型MyClass=
接口imy接口
成员。方法'T)和'T:>Exception>s=
设i=s.IndexOf“a”
如果i=-1,则引发(新的MyException