初始化包含字节数组的结构数组

时间:2018-03-02 21:43:53

标签: c# arrays struct initialization

struct a
{
int x;
int y;
byte[] z;
}

var b = new a[] {{0, 0, {0, 0, 0}}, {1,1, {1,1,1}}};

我想初始化一个结构数组,每个结构包含一个字节数组。我也尝试过:

var b = new a[] {{0, 0, new byte[] {0, 0, 0}}, {1,1, new byte[] {1,1,1}}};

2 个答案:

答案 0 :(得分:4)

构造函数会使其更加安排和可读:

struct a
{
    int x;
    int y;
    byte[] z;

    public a(int xv, int yv, byte[] zv)
    {
        x = xv;
        y = yv;
        z = zv;
    }
}

public void Initialize()
{
    var b = new a[] {new a(0,0,new byte[] { 0,0,0}),
    new a(1,1,new byte[] { 1,1,2})};
}

另一种方式根据您的评论  
 1.如果您将struct字段的访问修饰符声明为public     将能够使用object initializer and not with constructor初始化它们(构造函数是一种方法)  2.你可以使用静态类并立即调用该对象
 3.使b全局和公共(var只是本地关键字)以便调用它 从外面(我会使用更具描述性的名称,然后b)。

完整示例:

public class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("y value of index 1 is: {0}", General.b[1].y);
        Console.ReadLine();
    }
}

public static class General
{
    public static a[] b = new a[] { new a() { x = 0, y = 0, z = new byte[] { 0, 0, 0 }},
                                    new a() { x = 1, y = 1, z = new byte[] { 1, 1, 1 }}
        };
    public struct a
    {
        public int x;
        public int y;
        public byte[] z;
    }
}

答案 1 :(得分:0)

使用带有一些值的常规构造函数,稍后再写入数组内容:

public struct A
{
    const int Size = 256;
    // mutable structs are evil. 
    public int x, y;
    // At least make the arrays (not the contents) readonly
    readonly public byte[] a;
    readonly public byte[] b;

    public A(int x, int y)
    {
        this.x = x;
        this.y = y;
        this.a = new byte[Size];
        this.b = new byte[Size];
    }
}

class Program
{
    static void Main(string[] args)
    {
        var x = new A(48, 64);
        var y = new A(32, 24);

        x.a[4] = 1;
        y.b[127] = 31;
    }
}