读取和写入 3D 字符串数组

本文关键字:字符串 数组 3D 读取 | 更新日期: 2023-09-27 18:31:48

嗨,我正在尝试写入然后将 3d 字符串数组读取到文件中。数组声明为 theatre[5, 5, 9] 。我一直在寻找,但找不到任何我理解的东西。基本上只是在wp8应用程序中的页面之间切换。我该怎么做?任何帮助都非常感谢。谢谢。

读取和写入 3D 字符串数组

编辑:似乎您可以按原样直接在数组上使用BinaryFormatter.Serialize()。它是这样的:

using System.Runtime.Serialization.Formatters.Binary;
...    
// writing
FileStream fs = File.Open("...");
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, theArray);
// reading
string[,,] theArray;
FileStream fs = File.Open("...");
BinaryFormatter bf = new BinaryFormatter();
theArray = (string[,,])bf.Deserialize(fs);

第一个解决方案(如果二进制格式化程序失败,请尝试此操作):

您可以在 3D 和 1D 之间进行转换,如下所示:

struct Vector {
    public int x;
    public int y;
    public int z;
    Vector(int x, int y, int z)
    {
        this.x = x;
        this.y = y;
        this.z = z;
    }
}
Vector GetIndices3d(int i, Vector bounds)
{
    Vector indices = new Vector();
    int zSize = bounds.x * bounds.y;
    indices.x = (i % zSize) % bounds.x;
    indices.y = (i % zSize) / bounds.x;
    indices.z = i / zSize;
    return indices;
}
int GetIndex1d(Vector indices, Vector bounds)
{
    return (indices.z * (bounds.x * bounds.y)) +
        (indices.y * bounds.x) +
        indices.x;
}

然后,只需将 3D 数组转换为 1D 数组并将其序列化为文件即可。做相反的阅读。

string[] Get1dFrom3d(string[,,] data)
{
    Vector bounds = new Vector(data.GetLength(0), data.GetLength(1), data.GetLength(2));
    string[] result = new string[data.Length];
    Vector v;
    for (int i = 0; i < data.Length; ++i)
    {
        v = GetIndices3d(i, bounds);
        result[i] = data[v.x, v.y, v.z];
    }
    return result;
}
string[,,] Get3dFrom1d(string[] data, Vector bounds)
{
    string[,,] result = new string[bounds.x, bounds.y, bounds.z];
    Vector v;
    for (int i = 0; i < data.Length; ++i)
    {
        v = GetIndices3d(i, bounds);
        result[v.x, v.y, v.z] = data[i];
    }
    return result;
}

将数据序列化为文件取决于数据的内容。您可以选择未出现在任何数据中的分隔符,并使用分隔符连接字符串。

如果无法确定不同的分隔符字符,则可以在自己方便时选择一个,并对字符串进行预处理,以便对分隔符在数据中自然出现的位置进行转义。这通常是通过将分隔符插入字符串中出现的位置来完成的,使其显示为 twise。然后在读取文件时处理此问题(即:分隔符对=字符数据的自然出现)。

另一种方法是将所有内容转换为十六进制,并使用一些任意分隔符。这将或多或少地使文件大小增加一倍。

从您上一条评论中,似乎您不需要 3D 数组,即使依靠最快/最脏的方法,您也可以/应该使用 2D 数组。但是,您可以通过创建具有所需属性的自定义类来避免第二个维度。示例代码:

seat[] theatre = new seat[5]; //5 seats
int count0 = -1;
do
{
    count0 = count0 + 1; //Seat number
    theatre[count0] = new seat();
    theatre[count0].X = 1; //X value for Seat count0
    theatre[count0].Y = 2; //Y value for Seat count0
    theatre[count0].Prop1 = "prop 1"; //Prop1 for Seat count0
    theatre[count0].Prop2 = "prop 2"; //Prop2 for Seat count0
    theatre[count0].Prop3 = "prop 3"; //Prop3 for Seat count0
} while (count0 < theatre.GetLength(0) - 1);

其中seat由以下代码定义:

class seat
{
    public int X { get; set; }
    public int Y { get; set; }
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public string Prop3 { get; set; }
}