本文介绍了在.NET中有没有使用指针作为函数的参数或使用&QUOT之间的差额;参考"关键词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我写了一个结构和功能,在那里我试图通过引用传递的结构(即结构值可以在函数内部进行修改)。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 Pointerprivate 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关键字,上下文是安全的,并且无法更改,其中的客房指向,只有它的数据,如号,拍摄和类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. 这篇关于在.NET中有没有使用指针作为函数的参数或使用&QUOT之间的差额;参考"关键词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-28 06:34