我有以下代码框架:
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
的类型。我怎么能做到这一点?
答案 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