如何重写这段处理流和字节缓冲区的 C# 代码
How to rewrite this C# code that deals with a Stream and a byte buffer
我有这个 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)
但是可能有更实用的方法吗?
除了 Patryk 的评论观点:
这是一个非常紧迫的问题,所以它不会变得更漂亮。
我唯一想尝试改变的是重复的 read/writes - 可能是这样的:
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 ()
我有这个 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)
但是可能有更实用的方法吗?
除了 Patryk 的评论观点:
这是一个非常紧迫的问题,所以它不会变得更漂亮。
我唯一想尝试改变的是重复的 read/writes - 可能是这样的:
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 ()