【发布时间】:2015-01-08 21:13:34
【问题描述】:
如何覆盖内置集合(如 map 或序列)上的 tostring 函数,以便 printfn 使用这个新的自定义 tostring 函数?
我猜应该是这样的
type seq<'T> with
override xs.Tostring() =
"blabla"
但是这只会给出错误“类型缩写不能有扩充”。
然后我查看了msdn,发现以下关于类型扩展http://msdn.microsoft.com/en-us/library/dd233211.aspx
它指出我应该能够扩展例如 int32 和如下序列
type System.Int32 with
member this.FromString( s : string ) =
System.Int32.Parse(s)
type seq<'T> with
/// Repeat each element of the sequence n times
member xs.RepeatElements(n: int) =
seq { for x in xs do for i in 1 .. n do yield x }
第一个示例运行良好,但对于第二个示例,我收到一条错误消息,提示 “类型缩写不能包含成员”。
我目前正在使用 .Net 4.5.1 和 F# 3.1
【问题讨论】:
-
在 .NET 中一般无法完成,请参阅 this question。但是,您可以重新定义
printfn以使其工作。
标签: f#