在 VB.NET 中复制字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12969498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 15:59:11  来源:igfitidea点击:

Copy byte array in VB.NET

vb.netsqlitegarbage-collection

提问by tmighty

I am retrieving a byte blob from an SQLite database/record set. I am not experienced with garbage collection yet.

我正在从 SQLite 数据库/记录集中检索一个字节 blob。我还没有垃圾收集经验。

When I say:

当我说:

Dim bt() As Byte
bt = r.fields("mybyteblob").value

... is that okay or unsafe?

......这可以还是不安全?

I would like to make a copy of the byte array in the record set field, and I am not sure if I am simply referencing the byte array here instead of copying it.

我想在记录集字段中复制字节数组,我不确定我是否只是在这里引用字节数组而不是复制它。

采纳答案by Steve

In your code you are only referencing the byte array.
If you want to copy it you need

在您的代码中,您仅引用字节数组。
如果你想复制它,你需要

Dim bt() As Byte 
if r.fields("mybyteblob").Value Is not Nothing then 
    dim lenArray = r.fields("mybyteblob").Length
    bt = new Byte(lenArray)
    Array.Copy(r.fields("mybyteblob").value, bt, lenArray)
end if

There is another alternative.
The Buffer class is faster than Array and more appropriate because you are using a byte array

还有另一种选择。
Buffer 类比 Array 更快,更合适,因为您使用的是字节数组

Dim bt() As Byte 
if r.fields("mybyteblob").Value Is not Nothing then 
    dim lenArray = r.fields("mybyteblob").Length
    bt = new Byte(lenArray)
    Buffer.BlockCopy(r.fields("mybyteblob").value, 0, bt, 0, lenArray)
end if

Here a good questionon the two methods

这里有一个关于这两种方法的好问题

回答by Rolf Bjarne Kvinge

It is veryunusual to run into garbage collection problems if you only write managed code (i.e. no P/Invoke).

如果您只编写托管代码(即没有 P/Invoke),遇到垃圾收集问题是非常罕见的。

Many smart people has put a lot of effort into making garbage collection work without you having to worry about it, so do just that: don't worry about it. Just write your code, and if you run into a specific behavior you don't understand, then ask about that particular behavior (and I can assure you that in 99.9967% [1] of the cases it will not be the garbage collector).

许多聪明的人付出了很多努力让垃圾收集工作而无需您担心,所以就这样做:不要担心。只需编写您的代码,如果遇到您不理解的特定行为,请询问该特定行为(我可以向您保证,在 99.9967% [1] 的情况下,它不会是垃圾收集器)。

[1] This is not a random number. I've ran into a garbage collection gotcha once in ~10 years of programming. Assuming 10 bugs a day and 300 days of work per year, that makes 29999/30000 bugs which are not garbage-collection related = 99.9967%.

[1] 这不是随机数。在大约 10 年的编程生涯中,我遇到过一次垃圾收集问题。假设每天有 10 个错误,每年工作 300 天,那么与垃圾收集无关的错误为 29999/30000 = 99.9967%。