我有这个C#代码:
const int bufferLen = 4096;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = stream.Read(buffer, 0, bufferLen)) > 0)
{
outstream.Write(buffer, 0, count);
}
我需要在F#中重写它。我可以这样做:
let bufferLen : int = 4096
let buffer : byte array = Array.zeroCreate bufferLen
let count : int = 0
let mutable count = stream.Read(buffer, 0, bufferLen)
if count > 0 then
outstream.Write(buffer, 0, count)
while (count > 0) do
count <- stream.Read(buffer, 0, bufferLen)
outstream.Write(buffer, 0, count)
但是可能有一种更实用的方式吗?
答案 0 :(得分:4)
除了Patryk的评论观点:
这是一个非常迫切的问题,所以它不会变得更漂亮。
我唯一想改变的是重复读/写 - 也许是这样:
let copyInto (outstream : System.IO.Stream) (stream : System.IO.Stream) =
let bufferLen : int = 4096
let buffer : byte array = Array.zeroCreate bufferLen
let rec copy () =
match stream.Read(buffer, 0, bufferLen) with
| count when count > 0 ->
outstream.Write(buffer, 0, count)
copy ()
| _ -> ()
copy ()