码迷,mamicode.com
首页 > Windows程序 > 详细

C#中指针的简单使用

时间:2018-03-10 11:56:49      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:str   AC   log   简单例子   text   简单   支持   哈哈   delegate   

 

原来C#不仅仅支持和C/C++中指针(或者说是引用)很像的委托delegate,还支持在unsafe代码块中使用指针,从而写非托管的代码(人为不让垃圾回收机制来管理相应的内存)。在unsafe中就可以使用指针,基本用法和C++差不多(果然是一家人,哈哈)。

在用指针调用数组的时候需要使用fixed语句(只能在unsafe语句块中使用)来固定指针变量的初始值,否则可能被垃圾回收机制改变指针变量的值,fixed语句可以禁止垃圾回收机制重定位可移动的变量。

fixed语句中可以设置指向托管变量的指针,并且执行该语句期间可以固定某变量。

基本语法

   fixed (<需要固定的变量>)

     {   <fixed语句块,内部可以用指针对托管变脸操作>   }

下面上一个操作数组的简单例子:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.IO;
 7 using System.Collections.Generic;
 8 
 9 namespace CsharpStudy
10 {
11 
12    
13 
14 
15 
16     class Program
17     {
18 
19 
20         static void Main(string[] args)
21         {
22             /************Main function***************/
23 
24             unsafe 
25             {
26                 int[] list = new int[3]{10, 20, 30};
27 
28                 fixed (int* p = list)
29                 {
30                     for (int i = 0; i < 3; i++)
31                     {
32                         Console.WriteLine(*(p + i));
33                     }
34 
35                 }
36             }
37             
38 
39             /****************************************/
40             Console.WriteLine();
41             Console.ReadKey();
42         }
43     }
44 
45 
46 }

例子的结果图是

技术分享图片

 

 注意,在VS中运行unsafe的代码的时候需要在project的属性中找到bulid,勾选允许非安全的代码这一项。

C#中指针的简单使用

标签:str   AC   log   简单例子   text   简单   支持   哈哈   delegate   

原文地址:https://www.cnblogs.com/jeavenwong/p/8537610.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!