c++里面,我们很熟悉这两个东西.在c#里面他们也一样可以用,只不过含有他们的代码如果不在unsafe 标记下,编译器将会将它拒之门外.当然如果条件编译参数没有/unsafe 也是无法编译通过的(如果用vs.net集成编译环境,则在项目属性页-代码生成节将"允许不安全代码块"设置成true). &可以取得变量的地址,但是并不是所有的变量,托管类型,将无法取得其地址.c#里面,普通的值类型都是可以取得地址的,比如struct,int,long等,而class是无法取得其地址的,另外string是比较特殊的类型,虽然是值类型,但它也是受管的.这里插一下另一个运算符,sizeof,它也是仅可用于unsafe模式下.看下面这段代码,里面简单的用到了*,&,sizeof,还有c#里很少见但c++里大家很熟的->: class Class1 { struct Point { public int x; public int y; } public static unsafe void Main() { Point pt = new Point(); Point* pt1 = &pt; int* px = &(pt1->x); int* py = &(pt1->y); Console.WriteLine("Address of pt is :0x{0:X} ",(uint)&pt); Console.WriteLine("size of the struct :{0} ",sizeof(Point)); Console.WriteLine("Address of pt.x is :0x{0:X} ",(uint)&(pt.x)); Console.WriteLine("Address of pt.y is :0x{0:X} ",(uint)&(pt.y)); Console.WriteLine("Address of px is :0x{0:X} ",(uint)&(*px)); Console.WriteLine("Address of py is :0x{0:X} ",(uint)&(*py)); Console.ReadLine(); } } 我这里运行的输出结果是:Address of pt is :0x12F698 size of the struct :8 Address of pt.x is :0x12F698 Address of pt.y is :0x12F69C Address of px is :0x12F698 Address of py is :0x12F69C 可以看出struct的首地址与第一个成员变量的地址相同,而这个struct的长度是8个字节(=4+4).
{
struct Point
{
public int x;
public int y;
}
public static unsafe void Main()
{
Point pt = new Point();
Point* pt1 = &pt;
int* px = &(pt1->x);
int* py = &(pt1->y);
Console.WriteLine("Address of pt is :0x{0:X} ",(uint)&pt);
Console.WriteLine("size of the struct :{0} ",sizeof(Point));
Console.WriteLine("Address of pt.x is :0x{0:X} ",(uint)&(pt.x));
Console.WriteLine("Address of pt.y is :0x{0:X} ",(uint)&(pt.y));
Console.WriteLine("Address of px is :0x{0:X} ",(uint)&(*px));
Console.WriteLine("Address of py is :0x{0:X} ",(uint)&(*py));
Console.ReadLine();
}
}
我这里运行的输出结果是:Address of pt is :0x12F698
size of the struct :8
Address of pt.x is :0x12F698
Address of pt.y is :0x12F69C
Address of px is :0x12F698
Address of py is :0x12F69C
可以看出struct的首地址与第一个成员变量的地址相同,而这个struct的长度是8个字节(=4+4).
当定义一个指针,以数组的方式访问,就是你的这种方法。实际是改变了指针访问内存的方式,
因为A是指针,这个时候要先获得这个指针A中存放的地址,然后在这个地址上家上偏移i,
而对于一般数组而言,是直接就知道A的地址,而不需要在去内存获得的。C专家编程里专门讲到指针和数组