为什么不能在固定语句中使用属于类字段的结构?

时间:2019-07-09 05:20:21

标签: c# .net pointers

在这段代码中,我想从MyStruct类型创建一个指针,但是编译器向我显示此错误:“您不能使用给定表达式的地址”。 这是我的代码:

unsafe class Program
    {
        static void Main(string[] args)
        {
            Test test = new Test();

            //Error: You cannot take the address of given expression
            fixed (MyStruct* ms = &test.MyStruct) 
            {

            }

            fixed (int* a = &test.a) //Is OK
            {

            }

        }
    }

    unsafe class Test
    {
        public int a;
        public MyStruct MyStruct { get; set; } = new MyStruct();
    }

    unsafe struct MyStruct
    {
        public int A;
        public fixed int Ids[5];
        public int B;
    }

我不明白为什么会显示此错误。一切看起来还好吗? 谁能解释这段代码会发生什么?

1 个答案:

答案 0 :(得分:1)

您不能在固定声明的上下文中使用属性。如果您将MyStruct属性变成一个字段,它将起作用。

unsafe class Test
{
    public int a;
    public MyStruct MyStruct = new MyStruct();
}