【问题标题】:Initializing an array of structs that contain a array of bytes初始化包含字节数组的结构数组
【发布时间】:2018-08-11 04:24:28
【问题描述】:
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}}};

【问题讨论】:

  • 试试var b = new a[] {new a() {0, 0, new byte[] {0, 0, 0}}, new a() {1,1, new byte[] {1,1,1}}};
  • 我试过了,没有运气。

标签: c# arrays struct initialization


【解决方案1】:

构造函数会使其更有条理和可读性:

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.如果您将结构字段的访问修饰符声明为公共您 将能够使用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;
    }
}

【讨论】:

  • 我正在移植我用 C 编写的代码。在 C 中,此结构数组由编译器创建,无需在运行时运行任何代码。我知道这可能是最好的答案,但不得不在运行时创建它感觉有点尴尬。
  • @BingBang 现在你的问题更清楚了,请看我的编辑。
  • 谢谢@jonathana。我会在星期一试试。
  • 实际代码在struct数组中包含64个成员,每个struct成员包含一个256个成员的字节数组。这就是为什么我对在运行时创建它犹豫不决。
  • 我收到错误消息,指出由于保护级别而无法访问元素
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2020-05-28
    • 2022-12-03
    • 2015-05-04
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 1970-01-01
    • 2015-07-29
    相关资源
    最近更新 更多