如何在其方法中获取结构的地址?

How to get address of a struct inside its method?

我能够在其(实例)方法之外获取结构的地址,如下所示:

public struct Values
{
    public byte A;
    public byte B;
    public byte C;
    public byte D;

    public static unsafe bool Equals(Values lhs, Values rhs)
    {
        return *(int*) &lhs == *(int*) &rhs;
    }
}

但是当我尝试获取结构本身的地址时,IDE 告诉我这是错误的:

    public unsafe bool Equals(Values other)
    {
        return *(int*) &this == *(int*) &other;
    }

错误信息是:

You can only take the address of an unfixed expression inside of a fixed statement initializer.

fixed 语句防止垃圾收集器重定位可移动变量。 但是这个struct不是可移动变量,不会被垃圾回收吧?

已更新

我实际需要的是get/set索引第N个字节的值。虽然我可以通过 switch 语句来完成,但是通过索引会更快。 感谢@KonradKokosa,Fixed Size Buffer 满足了我的需求。 我还是想知道主要问题的答案。

您不能在结构实例方法中获取 this 的地址,因为 “此结构不是可移动变量” 不是正确的陈述。结构可以装箱,因此它立即变得可移动。实例方法不知道它是从盒装调用还是从 not-boxed 结构调用。

请注意,它目前也是 ref struct 的长期限制,但可以取消。所以,下面的代码仍然会产生相同的编译错误:

public ref struct C {
    public void M() {
        var ptr = &this;
    }
}

但是,您可以在第一个片段中获取结构的地址:

public static unsafe bool Equals(Values lhs, Values rhs)
{
    return *(int*) &lhs == *(int*) &rhs;
}

因为您在这里获取局部参数的地址,按值传递(最后是 Values 的副本)。