C# - Cast a byte array to an array of struct and vice-versa (reverse)

后端 未结 5 1110
刺人心
刺人心 2021-01-19 17:05

I would like to save a Color[] to a file. To do so, I found that saving a byte array to a file using \"System.IO.File.WriteAllBytes\" should be very efficient.

I wou

5条回答
  •  迷失自我
    2021-01-19 17:53

    Regarding Array Type Conversion

    C# as a language intentionally makes the process of flattening objects or arrays into byte arrays difficult because this approach goes against the principals of .NET strong typing. The conventional alternatives include several serialization tools which are generally seen a safer and more robust, or manual serialization coding such as BinaryWriter.

    Having two variables of different types point to the same object in memory can only be performed if the types of the variables can be cast, implicitly or explicitly. Casting from an array of one element type to another is no trivial task: it would have to convert the internal members that keep track of things such as array length, etc.

    A simple way to write and read Color[] to file

    void WriteColorsToFile(string path, Color[] colors)
    {
        BinaryWriter writer = new BinaryWriter(File.OpenWrite(path));
    
        writer.Write(colors.Length);
    
        foreach(Color color in colors)
        {
            writer.Write(color.ToArgb());
        }
    
        writer.Close();
    }
    
    Color[] ReadColorsFromFile(string path)
    {
        BinaryReader reader = new BinaryReader(File.OpenRead(path));
    
        int length = reader.ReadInt32();
    
        Colors[] result = new Colors[length];
    
        for(int n=0; n

提交回复
热议问题