我已经写了结构和功能,其中我尝试通过引用传递的结构(即结构值可以在里面的功能被修改)。
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);
}
}
现在通过引用传递这个结构,我发现有两种方式。
//Using Pointer
private unsafe static void Reserve(HotelRoom* room)
{
if (room->Taken)
Console.WriteLine("Cannot reserve room {0}", room->Number);
else
room->Taken = true;
}
//Using ref keyword.
private static void Reserve(ref HotelRoom room)
{
if (room.Taken)
Console.WriteLine("Cannot reserve room {0}", room.Number);
else
room.Taken = true;
}
有什么区别吗? 通常,当我应该使用指针,什么时候应该去ref关键字?