在堆栈上创建固定大小的数组

Create fixed size array on stack

我需要一个固定的数据结构(出于性能原因)在堆栈上进行管理,但其行为类似于数组

我知道我可以创建这样的东西:

using System;

namespace X
{
    public sealed struct CustomArray<T>
    {
        private const Int32 n = 2;

        private T _field_1;
        private T _field_2;
        // ...
        private T _field_n;

        public T this[Int32 idx]
        {
            get
            {
                switch(idx)
                {
                    case (0): return _field_1;
                    case (1): return _field_2;
                    // ...
                    case (n): return _field_n;

                    default: throw new IndexOutOfRangeException();
                }
            }
            set
            {
                switch(idx)
                {
                    case (0): _field_1 = value; break;
                    case (1): _field_2 = value; break;
                    // ...
                    case (n): _field_n = value; break;

                    default: throw new IndexOutOfRangeException();
                }
            }
        }
    }
}

但这对于包含约 50 个元素的结构来说并不是很方便。有没有办法以更方便和可维护的方式实现这一目标?

提前致谢

你可以使用stackalloc关键字在堆栈中分配一个数组,看起来它会满足你的堆栈分配需求。不幸的是,它要求您处于不安全的环境中。

int* block = stackalloc int[100];

另一种选择是将具有命名字段的数据结构声明为结构,并在堆栈上创建它(如局部变量)。如果您需要像访问堆栈中的数据一样访问数组,您可以这样做:

[StructLayout(LayoutKind.Explicit, Size=16, CharSet=CharSet.Ansi)]
public unsafe struct DataStructure
{
    [FieldOffset(0)]public fixed ushort[8];

    [FieldOffset(0)]public ushort wYear; 
    [FieldOffset(2)]public ushort wMonth;
    [FieldOffset(4)]public ushort wDayOfWeek; 
    [FieldOffset(6)]public ushort wDay; 
    [FieldOffset(8)]public ushort wHour; 
    [FieldOffset(10)]public ushort wMinute; 
    [FieldOffset(12)]public ushort wSecond; 
    [FieldOffset(14)]public ushort wMilliseconds; 
}

然后你可以这样引用它:

private static unsafe void Main(string[] args)
{
    DataStructure ds;

    ds.wYear = 2015;
    ds.wMonth = 04;

    ds.array[0] = 2014;
    ds.array[1] = 05;
}