代码之家  ›  专栏  ›  技术社区  ›  Bing Bang

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

  •  -1
  • Bing Bang  · 技术社区  · 6 年前
    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 回复  |  直到 6 年前
        1
  •  2
  •   Jonathan Applebaum    6 年前

    构造器将使其更具安排性和可读性:

    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、如果将结构字段的访问修饰符声明为public,则 将能够使用 object initializer and not with constructor (构造函数是一种方法)。
    2、可以使用静态类并立即调用该对象
    3、品牌 b global和public(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;
        }
    }
    
        2
  •  0
  •   John Alexiou    6 年前

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

    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;
        }
    }