(63)C# 不安全代码unsafe
编译不安全代码
有三种方式编译不安全代码
1勾选不安全代码

或者在工程文件中做设置

2.使用cli编译
dotnet build /property:AllowUnsafeBlocks=True
dotnet run
3.直接调用编译器
csc.exe /unsafe Program.cs
再运行编译好的文件

标记不安全代码
1.指定不安全代码方法
unsafe static void Main() { }
2.指定不安全代码块
static void Main() { unsafe { } }
指针
1.指针声明
//这里的b是指向int类型的指针 int* b;
指针的类型不能是非托管类型以外的类型,如:引用类型或者泛型
//错误,string是引用类型 string* b;
也不能包含引用类型
static void Main() { unsafe { Student* stu; } } struct Student { int age; //报错 string name; }
2.指针赋值
unsafe static void Main() { int a = 10; //使用寻址操作符获取地址 int* p = &a; //打印a的地址,并用16进制输出 Console.WriteLine("Hex: {0:X}", (int)p); Console.ReadKey(); }
3.指针解引用
4.访问被引用类型
通过委托执行不安全代码
unsafe
fixed
stackalloc
void*

浙公网安备 33010602011771号