一 编译预处理
1 标识符声明
① #define定义一个标识符;
② #undef 取消定 一个标识符;
2 条件处理
#if #elif #else #endif
3 信息报告
#error和#warning
4 行号标记
#line 行号“文件名”
二 unsafe及指针
1 unsafe
用于修饰类、方法等
2 fixed及指针
fixed(类型*指针名=表达式)语句;
3 sizeof运算符
sizeof(简单或结构类型名)
4 stackalloc
在栈上分配的内存,而不是在堆上,因此不会担心内存被垃圾回收器自动回收;
5 指针示例
class FileStream:Stream
{
int handle;
[dllimport("kernel32",SetLastError=true)]
static extern unsafe bool ReadFile(int hFile,
void*lpBuffer,int nBytesToRead,
int* nBytesRead,Overlapped*lpOverlapped);
public unsafe int Read(byte[] buffer,int index,int count)
{
int n=0;
fixed(byte*p=buffer)
{
ReadFile(handle,p+index,count,&n,null);
}
return n;
}
}
指针
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 指针
{
class Test
{
static unsafe void Copy(byte[] src, byte[] dst, int count)
{
int srcLen = src.Length;
int desLen = dst.Length;
if(srcLen<count||desLen<count)
{
throw new ArgumentException();
}
fixed(byte* pSrc=src,pDst=dst)
{
byte* ps = pSrc;
byte* pd = pDst;
for(int n=0;n<count;n++)
{
*pd++ = *ps++;
}
}
}
static void Main()
{
byte[] a = new byte[100];
byte[] b= new byte[100];
for (int i = 0; i < 100; ++i)
a[i] = (byte)i;
Copy(a, b, 100);
Console.WriteLine("The first 10 elements are:");
for (int i = 0; i < 10; ++i)
Console.Write(b[i] + "{0}", i < 9 ? " " : " ");
Console.WriteLine("\n");
Console.ReadKey();
}
}
}
stackalloc分配内存空间
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 分配内存空间
{
class Test
{
unsafe static string IntToString(int value)
{
char* buffer = stackalloc char[16];
char* p = buffer + 16;
int n = value >= 0 ? value : -value;
do
{
*--p = (char)(n % 10 + '0');
n /= 10;
} while (n != 0);
if (value < 0) *--p = '-';
return new string(p, 0, (int)(buffer + 16 - p));
}
static void Main()
{
Console.WriteLine(IntToString(12345));
Console.WriteLine(IntToString(-999));
Console.ReadKey();
}
}
}