当需要固定块时,我有点困惑。我有例子,给了我下面的一个矛盾的情形:固定块in .net
enum RoomType { Economy, Buisness, Executive, Deluxe };
struct HotelRoom
{
public int Number;
public bool Taken;
public RoomType Category;
public void Print()
{
String status = Taken ? "Occupied" : "available";
Console.WriteLine("Room {0} is of {1} class and is currently {2}", Number, Category, status);
}
}
我已经作出安排,采取一个指向HotelRoom
private unsafe static void Reserve(HotelRoom* room)
{
if (room->Taken)
Console.WriteLine("Cannot reserve room {0}", room->Number);
else
room->Taken = true;
}
在main方法的功能我有以下几点:
unsafe static void Main(string[] args)
{
HotelRoom[] myfloor = new HotelRoom[4];
for (int i = 0; i < myfloor.Length; i++)
{
myfloor[i].Number = 501 + i;
myfloor[i].Taken = false;
myfloor[i].Category = (RoomType)i;
}
HotelRoom Room = myfloor[1];
Reserve(&Room); //I am able to do this without fixed block.
//Reserve(&myfloor[1]); //Not able to do this so have to use fixed block below.
fixed (HotelRoom* pRoom = &myfloor[1])
{
Reserve(pRoom);
}
myfloor[1].Print();
Room.Print();
}
我的困惑是,我能够做到Reserve(&Room)
但不Reserve(&myfloor[1])
。我认为他们正在做同样的事情 - 将HotelRoom
结构的存储地址传递给Reserve
函数。为什么我需要fixed
来做到这一点?
得到了我完全错过了这一点..你immdeiately指出。谢谢。 – Pritesh 2012-04-19 12:10:43