在C#中,可以使用關鍵字unsafe來聲明非類型安全的代碼塊,從而使用指針。指針賦值的方法如下所示:
unsafe
unsafe { int x = 10; int* ptr = &x; // 賦值為變量x的地址 Console.WriteLine(*ptr); // 輸出變量x的值 }
需要注意的是,使用指針需要在項目屬性中啟用Allow unsafe code選項。此外,指針操作具有一定的風險,因此應謹慎使用。
Allow unsafe code