Welcome

首页 / 软件开发 / C# / C# 之不安全代码(1)

C# 之不安全代码(1)2010-06-05 cnblogs.com DiggingDeeply主要参考的是C# Language Specification Version 3.0。

引子

C#是.Net平台上主流的开发语言,和经典的C/C++不同的是,C#所编写的代码是托管代码,由GC来管理内存,省去了new/delete的烦恼。但是,由于某些特殊的要求,比如和底层的操作系统接口,访问内存映射设备或者实现对时间要求苛刻的算法时,C#提供了不安全代码。

不安全上下文

不安全代码只能写在不安全上下文中。

通过unsafe 修饰符可以修饰:

class, struct, interface, or delegate

field, method, property, event, indexer, operator, instance constructor, destructor, or static constructor

unsafe-statement-block

指针的类型

在不安全上下文中,指针类型和引用类型或是值类型一样。但是,指针类型可以用在不安全上下文之外的typeof中,虽然这么做不安全。

Type t = typeof(Int32*);返回的是System.Int32*

指针类型是用非托管类型或是void加上*来表示的。

pointer-type:
unmanaged-type *
void *

unmanaged-type:
type

在*前面的指针类型被称为指针类型的引用类型。它表明了指针变量的值指向的变量的类型。

非托管类型不是引用类型,也不包含任何嵌套的引用类型的成员。

非托管类型就是下面的一种:

·sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool.

·Any enum-type.

·Any pointer-type.

·Any user-defined struct-type that contains fields of unmanaged-types only.

例子:

ExampleDescription
byte*Pointer to byte
char*Pointer to char
int**Pointer to pointer to int
int*[]Single-dimensional array of pointers to int
void*Pointer to unknown type