简体   繁体   English

结构内部的c#2D数组

[英]c# 2D Array inside a Struct

I need to return a struct from a method. 我需要从方法返回一个结构。 One of the members of the struct needs to be a 2D array. 结构的成员之一必须是2D数组。 I am aware of using fixed size buffers to declare the size of the array in the struct and of using 我知道使用固定大小的缓冲区来声明结构体中数组的大小,并且使用

[StructLayout(LayoutKind.Explicit)]
public struct struct1
{
    [FieldOffset(0)]
       ....
}

but here is the issue. 但这是问题。 I cannot do this as I do not know the length of the array ahead of time. 我无法执行此操作,因为我不提前知道数组的长度。 The size of the array depends on parameters chosen by the user at runtime. 数组的大小取决于用户在运行时选择的参数。

struct foo {
    int x;
    double[,]  A = new double[N, M];
};

I do not know N or M ahead of time. 我不提前知道N或M。 They are selected by the user at runtime. 用户在运行时选择它们。

Is this possible? 这可能吗? If yes, how would one do it? 如果是,怎么办? Thank you in advance for any suggestions or advice you may be able to provide. 预先感谢您可能提供的任何建议。

It is not possible to inline a variable sized array because structs must have fixed size known at compile time. 不能内联可变大小的数组,因为结构必须具有在编译时已知的固定大小。 You can of course have a reference to an array of a size only known at runtime. 您当然可以引用一个只有在运行时才知道的大小的数组。

internal struct Foo
{
   internal Double[,] bar;

   internal Foo(Int32 sizeX, Int32 sizeY)
   {
     this.bar = new Double[sizeX, sizeY];
   }
}

You can use this struct like this 您可以像这样使用此结构

private function Foo InitializeFoo(Int32 sizeX, Int32 sizeY)
{
   var foo = new Foo(sizeX, sizeY);

   for (var y = 0; y < sizeY; y++)
   {
      for (var x = 0; x < sizeX; x++)
      {
         foo.bar[x, y] = x * y;
      }
   }

   return foo;
}

and calling this method like 并像这样调用此方法

var foo = InitializeFoo(12, 34);

will give you an instance of Foo with the field bar referencing a Double array of dimension 12 x 34. 将为您提供Foo实例,其中的字段栏引用尺寸为12 x 34的Double数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM