您的位置:首页 > 编程语言 > C#

C# 可否对内存进行直接的操作?

2015-10-19 10:37 519 查看
可以,用 unsafe。用的时候记得在项目属性(Properties)->生成(Build)->常规(General)中钩上允许不安全代码 (Allow unsafe code)。
否则会出现这个错误:Unsafe code may only appear if compiling with /unsafe。

// compile with: /unsafe using System; class UnsafeTest { // Unsafe method: takes pointer to int: unsafe static void SquarePtrParam(int* p) { *p *= *p; } unsafe static void Main() { int i = 5; // Unsafe method: uses address-of operator (&): SquarePtrParam(&i); Console.WriteLine(i); } } // Output: 25

// compile with: /unsafe

using System;
class UnsafeTest
{
// Unsafe method: takes pointer to int:
unsafe static void SquarePtrParam(int* p)
{
*p *= *p;
}

unsafe static void Main()
{
int i = 5;
// Unsafe method: uses address-of operator (&):
SquarePtrParam(&i);
Console.WriteLine(i);
}
}
// Output: 25


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: