固定和不安全有什么区别?(What is the difference between Fixed and Unsafe)

编程入门 行业动态 更新时间:2024-10-26 14:33:40
固定和不安全有什么区别?(What is the difference between Fixed and Unsafe)

为什么有两种不同的方式在.NET中锁定内存? 他们有什么区别?

Why are there 2 different ways lock memory in place in .NET? What is the difference between them?

最满意答案

固定语句用于不安全修饰符的上下文中。 不安全声明您将使用指针算术(例如:低级API调用),该算法不在正常的C#操作中。 固定语句用于锁定内存,以便垃圾收集器在仍处于使用状态时不会重新分配内存。 您不能在不安全的情况之外使用固定语句。

public static void PointyMethod(char[] array) { unsafe { fixed (char *p = array) { for (int i=0; i<array.Length; i++) { System.Console.Write(*(p+i)); } } } }

The fixed statement is used in the context of the unsafe modifier. Unsafe declares that you are going use pointer arithmetic(eg: low level API call), which is outside normal C# operations. The fixed statement is used to lock the memory in place so the garbage collector will not reallocate it while it is still in use. You can’t use the fixed statement outside the context of unsafe.

Example

public static void PointyMethod(char[] array) { unsafe { fixed (char *p = array) { for (int i=0; i<array.Length; i++) { System.Console.Write(*(p+i)); } } } }

更多推荐

本文发布于:2023-07-28 04:34:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1300409.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不安全   有什么区别   difference   Fixed   Unsafe

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!