我写了一个结构和函数,我尝试通过引用传递结构(即结构值可以在函数内部修改)。
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 关键字?