我有下面的例子:“隐式重载”可能吗?
所有的type Stream (capacity) =
let data = Array.zeroCreate capacity
member private s.position = ref 0
static member private encoder = new Text.UTF8Encoding()
static member private write (x, o, a : byte[]) = for i = 0 to 3 do a.[o + i] <- byte((x >>> 24 - i * 8) % 256)
static member private write (x, o, a : byte[]) = for i = 0 to 1 do a.[o + i] <- byte((x >>> 24 - i * 8) % 256s)
static member private write (x : string, o : int, a : byte[]) = Stream.encoder.GetBytes(x, 0, x.Length, a, o)
static member format (x : int, s) = let a = Array.create s 0uy in Stream.write(x, 0, a); a
static member format (x : int16, s) = let a = Array.create s 0uy in Stream.write(x, 0, a); a
static member format (x : string, s) = let a = Array.create s 0uy in Stream.write(x, 0, a); a
首先,比较遗憾的是非常混乱的代码,我只是在F#初学者。您可能会看到三个format
重载仅在参数类型上有所不同,而它们的主体是相同的(尽管调用了不同的重载write
)。可能以某种方式将格式函数减少为1,也许内联?
我很抱歉万一我完全忽略了这一点,但我找不到有关此事的很多信息。
这看起来像[模式匹配](http://msdn.microsoft.com/en-us/library/dd233242.aspx)可能更适合。 – 2012-01-11 23:39:35
有没有办法做到这一点,没有拳击x? – user1098567 2012-01-11 23:44:31
这是一个很好的问题......你写这个的方式看起来更像是一个OO程序,而不是一个功能性的程序。 – 2012-01-11 23:47:36