使用数组时,CLR会确保索引不超过数组的上下限,这样可以防止访问数组以外的内存,但是CLR在做这种检查时会有一定的性能代价,对于经常使用的代码(数组),可以使用非安全的代码,不让CLR进行代码的检查,下面是个简单的Demo,在代码中直接访问内存的例子
using System
public class MyClass
{
unsafe static MyArray()
{
//创建一个数组
int arr={1,3,5};
//获取指向数组开始位置的指针
fixed(int* element=&arr[0])
{
for(int i=0;i<arr.Length;i++)
{
Console.WriteLine(element[i]);
}
}
Console.ReadLine();
}
}
输出结果打出:1 2 3
相关文章:
-
2021-05-21
-
2022-01-01
-
2021-11-28
-
2022-12-23
-
2021-10-19
-
2021-09-07
-
2021-12-06
猜你喜欢
-
2022-01-13
-
2021-10-05
-
2021-06-19
-
2022-12-23
-
2022-02-10
相关资源
-
下载
2021-06-22
-
下载
2022-12-04
-
下载
2023-02-27
-
下载
2021-07-05