[英]How to implement generics with type annotations in F#
I have the following skeleton of code: 我有以下代码框架:
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
However, I am getting the following message: 但是,我收到以下消息:
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'.
类型变量“ T”已被约束为类型“ obj”。
and when compiled, obj
is passed to MyException instead of 'T
. 并且在编译时,
obj
传递给MyException而不是'T
I need to have the above type constraints on IMyInterface.Method
, and also need to pass the type passed into MyException
in MyClass.Method
. 我需要在
IMyInterface.Method
上具有上述类型约束,并且还需要将传递给MyClass.Method
MyException
的类型传递。 How can I accomplish this? 我该怎么做?
I think you have to parametrise MyClass
: 我认为您必须参数化
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
or repeat constraints on your method: 或对您的方法重复约束:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.