如何在 C# 中的不安全块中声明指向 class 对象的指针

How to declare a pointer to a class object in an unsafe block in C#

我不能像下面这样声明一个指向我自己的 class 对象的指针变量吗?

static void Main() {
    MyClass myClass = new MyClass();
    unsafe {
        fixed (MyClass* pMyClass = &myClass) {
            /// Do Somthing here with pMyClass..
        }
    }
}

此页面解释了原因:https://msdn.microsoft.com/en-us/library/y31yhkeb.aspx

C# 不允许指向引用的指针:

A pointer cannot point to a reference or to a struct that contains references, because an object reference can be garbage collected even if a pointer is pointing to it. The garbage collector does not keep track of whether an object is being pointed to by any pointer types.

您可能会争辩说 fixed 关键字应该允许这样做,因为它会阻止 GC 收集对象。这可能是正确的,但请考虑这种情况:

class Foo {
    public SomeOtherComplicatedClassAllocatedSeparatley _bar;
}

unsafe void Test() {
    Foo foo = new Foo();
    foo._bar = GetComplicatedObjectInstanceFromSomePool();

    fixed(Foo* fooPtr = &foo) {
        // what happens to `_bar`?
    }
}

fixed 关键字不能超出任何已取消引用的成员,它无权固定引用成员 _bar

现在可以说它仍然应该可以固定一个不包含其他引用成员的对象(例如一个简单的 POCO)并且可以固定一个 String 实例,但是由于某些原因 C#语言设计者刚刚决定禁止固定对象实例。