7

在 F# Interactive (fsi) 中,您可以使用AddPrinterAddPrinterTransformer为交互式会话中的类型提供漂亮的打印。如何为泛型类型添加这样的打印机?对类型使用通配符_不起作用:

> fsi.AddPrinter(fun (A : MyList<_>) -> A.ToString());;

只是没有使用打印机。

放入类型参数也会发出警告:

> 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'.

这也不是我想要的。

4

1 回答 1

8

这不适用于一般情况,但由于看起来您正在使用自己的类型(至少在您的示例中),并且假设您不想影响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)

输出:

> MyList([1;2;3])
val it : MyList<int> = [1; 2; 3]

对于第三方泛型类型,您可以使用AddPrintTransformer和反射来获取要显示的值。如果您有源代码,界面会更容易。

于 2013-02-21T22:22:35.247 回答