在.NET中有没有使用指针作为函数的参数或使用&QUOT之间的差额;参考"关键词?中有、差额、指针、函数

2023-09-04 04:16:42 作者:抱着你就抱着全世界

我写了一个结构和功能,在那里我试图通过引用传递的结构(即结构值可以在函数内部进行修改)。

I have written a struct and functions where I try to pass the struct by reference (i.e. struct value can be modified inside functions).

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);
    }
}

现在通过引用我发现两种方式传递这个结构。

Now to pass this struct by reference I've found two ways.

//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关键字?

Is there any difference? In general when should I use a pointer and when should I go for the ref keyword?

推荐答案

指针被认为是不安全的。

Pointers are considered unsafe.

如果您$在不安全的情况下C $ C,像传递引用由函数指针,一个人可以改变你的指针的指针别的地方,你会得到垃圾数据。

If you code in an unsafe context, like passing a reference by pointer to the function, someone can change your pointer to pointer somewhere else, and you get garbage data.

如果您使用ref关键字,上下文是安全的,并且无法更改,其中的客房指向,只有它的数据,如号,< STRONG>拍摄和类

If you use the ref keyword, the context is "safe", and you can't change where room is pointing to, only it's data like number, taken and category.

 
精彩推荐
图片推荐