获取变量的地址位置

Cor*_*ius 2 c#

C#如何在不使用unsafe关键字的情况下获取变量的地址.我不想更改地址或访问它,只是有它的位置.

Dan*_*rth 17

你不能.
并且有充分的理由,因为地址不固定.它可以 - 并且将 - 通过CLR的内存管理来移动.


D S*_*ley 7

由于.NET一直在托管内存中移动变量,因此需要"固定"变量,然后通过以下方式获取其位置GCHandle:

static void Main()
{

    string myVar = "This is my string";

    GCHandle handle = GCHandle.Alloc(myVar, GCHandleType.Pinned);
    IntPtr pointer = GCHandle.ToIntPtr(handle);

    Console.WriteLine(pointer);

    handle.Free();

}
Run Code Online (Sandbox Code Playgroud)

但是,我相信这实际上会将原始变量移动到由其引用的位置GCHandle,并且它不适用于所有类型 - 仅限于blittable类型.