固定和不安全有什么区别?(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)); } } } }更多推荐
发布评论