在F#Interactive(fsi)中,您可以使用AddPrinter或AddPrinterTransformer为交互式会话中的类型提供漂亮的打印.如何为通用类型添加此类打印机?使用该_类型的通配符不起作用:
> fsi.AddPrinter(fun (A : MyList<_>) -> A.ToString());;
Run Code Online (Sandbox Code Playgroud)
不使用打印机.
输入类型参数也会发出警告:
> fsi.AddPrinter(fun (A : MyList<'T>) -> A.ToString());;
  fsi.AddPrinter(fun (A : MyList<'T>) -> A.ToString());;
  -------------------------------^^
d:\projects\stdin(70,51): warning FS0064: This construct causes code
to be less generic than indicated by the type annotations. The type
variable 'T been constrained to be type 'obj'.
Run Code Online (Sandbox Code Playgroud)
这也不是我想要的.
这不适用于一般情况,但因为看起来你正在使用自己的类型(至少在你的例子中),并假设你不想影响ToString,你可以这样做:
type ITransformable =
  abstract member BoxedValue : obj
type MyList<'T>(values: seq<'T>) =
  interface ITransformable with
    member x.BoxedValue = box values
fsi.AddPrintTransformer(fun (x:obj) ->
  match x with
  | :? ITransformable as t -> t.BoxedValue
  | _ -> null)
Run Code Online (Sandbox Code Playgroud)
输出:
> MyList([1;2;3])
val it : MyList<int> = [1; 2; 3]
Run Code Online (Sandbox Code Playgroud)
对于第三方泛型类型,您可以使用AddPrintTransformer和反射来获取要显示的值.如果您有源,则界面更容易.