我有下面的例子:「隱式重載」可能嗎?
所有的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