固定ブロックが必要な場合に少し混乱しています。以下に矛盾するシナリオを与える例があります。
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;
}
メインメソッドには次のものがあります。
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
を行う必要があるのですか?