Skip to main content
 首页 » 编程设计

c#之当我添加新数据时,列表项目会发生变化……为什么

2024年02月23日22zfyouxi

我有一种方法可以将文件转换为字节,以便稍后可以通过 Internet 发送它。无论如何,因为我打算发送大文件,所以我发送文件 block 而不是发送整个文件。每个 block 由一个字节数组 (byte[]) 组成。我对这一切都不熟悉,所以我想在发送之前将每个 block 保存在一个 block 列表 (List) 中。所以我的课看起来像:

public class SomeClass 
{ 
 
    public List<byte[]> binaryFileList; 
 
    public void SendChunk(byte[] data, int index) 
    { 
        binaryFileList.Add(data); 
        // later I will add code in here to do something with data 
    } 
 
    public void test(string path) 
    { 
        binaryFileList = new List<byte[]>(); 
 
        System.IO.FileStream stream = new System.IO.FileStream(path, 
            System.IO.FileMode.Open, System.IO.FileAccess.Read); 
 
        var MaxChunkSize = 10000; 
        byte[] chunk = new byte[MaxChunkSize]; 
        while (true) 
        { 
            int index = 0; 
            // There are various different ways of structuring this bit of code. 
            // Fundamentally we're trying to keep reading in to our chunk until 
            // either we reach the end of the stream, or we've read everything we need. 
            while (index < chunk.Length) 
            { 
                int bytesRead = stream.Read(chunk, index, chunk.Length - index); 
 
                if (bytesRead == 0) 
                { 
                    break; 
                } 
                index += bytesRead; 
            } 
            if (index != 0) // Our previous chunk may have been the last one 
            { 
                SendChunk(chunk, index); // index is the number of bytes in the chunk 
            } 
            if (index != chunk.Length) // We didn't read a full chunk: we're done 
            { 
                return; 
            } 
        } 
 
 
    } 
} 

当我执行时:

SomeClass s = new SomeClass(); 
s.test(@"A:\Users\Tono\Desktop\t.iso"); 

binaryFileList 列表填充了文件 block :A:\Users\Tono\Desktop\t.iso

现在,当我试图从该数据创建一个文件时,问题就来了。调试时我注意到问题是因为当我输入数据时 binaryFileList 中的项目发生了变化。让我告诉你我的意思:

请注意,在此调试中,这是我第一次向 binaryFileList 添加项目。您还可以在数组中看到该项目的每个字节...

现在我将让该方法运行更多次,将更多项目添加到 binaryFileList。

所以现在 binaryFileList 有 278 个项目,而不是像上一张图​​片那样:

到目前为止一切看起来都还不错吧?但是你们是否记得 binaryFileList 的第一项包含一个几乎全为 0 的字节数组?看一下 binaryFileList 的第一项:

当我不断向 binaryFileList 添加项目时,请注意第一个项目是如何变化的:

换句话说,binaryFileList 是 byte[] 的列表。当我将 byte[] 添加到 binaryFileList 时,其他 byte[] 不应更改。他们确实改变了!为什么!?

请您参考如下方法:

以下行必须进入循环:

byte[] chunk = new byte[MaxChunkSize]; 

您只创建一次 block ,每次都用新数据覆盖它。您在列表中存储的只是对此 block 的引用,而不是它的副本。