且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#将字符串复制到字节缓冲区

更新时间:2023-11-27 22:30:34

如果缓冲区足够大,您可以直接将其编写:

If the buffer is big enough, you can just write it directly:

encoding.GetBytes(mystring, 0, mystring.Length, buffer, 0)

但是,您可能需要先检查长度;一个测试可能是:

However, you might need to check the length first; a test might be:

if(encoding.GetMaxByteCount(mystring.length) <= buflen // cheapest first
   || encoding.GetByteCount(mystring) <= buflen)
{
    return encoding.GetBytes(mystring, 0, mystring.Length, buffer, 0)
}
else
{
    buffer = encoding.GetBytes(mystring);
    return buffer.Length;
}

之后,无事可做,因为您已经通过 ref 传递了 buffer 。就我个人而言,我怀疑,但是这个 ref 是一个错误的选择。除非您是从头开始复制,即

after that, there is nothing to do, since you are already passing buffer out by ref. Personally, I suspect that this ref is a bad choice, though. There is no need to BlockCopy here, unless you were copying from a scratch buffer, i.e.

var tmp = encoding.GetBytes(mystring);
// copy as much as we can from tmp to buffer
Buffer.BlockCopy(tmp, 0, buffer, 0, buflen);
return buflen;