-1

我正在尝试在结构内分配堆栈数组。好吧,我的意思是指针。但我希望在没有额外代码的情况下完成分配,因为我在编写代码时知道大小(我不想new在创建结构时做很多事情)。如果我什至可以在没有unsafe上下文的情况下做到这一点,那就完美了。我尝试了一些东西,但效果不佳。我是 C# 的新手,所以可能有一种我没有看到的方法!

public struct TestValue {int value; }

[StructLayout(LayoutKind.Sequential)]
public struct TestArray {
   [MarshalAs(UnmanagedType.ByValArray, SizeConst=128)] public TestValue[] s1;
}

public struct TestSpan
{
    Span<TestValue> data= stackalloc TestValue[10];
}
4

1 回答 1

1
using System.Runtime.InteropServices;

public struct TestValue {int value; }

[StructLayout(LayoutKind.Sequential)]
public struct TestArray {
   [MarshalAsAttribute(UnmanagedType.ByValArray, SizeConst=128)] public TestValue[] s1;
}

public class Foo
{
    void test()
    {
        TestArray test = new TestArray();
        test.s1[10] = new TestValue();
    }
}

最后我只需要一点点改变!

于 2018-12-15T14:39:34.393 回答