什么时候需要在C#中使用stackalloc关键字? [英] When would I need to use the stackalloc keyword in C#?

查看:649
本文介绍了什么时候需要在C#中使用stackalloc关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

stackalloc关键字提供什么功能?我什么时候以及为什么要使用它?

What functionality does the stackalloc keyword provide? When and Why would I want to use it?

推荐答案

来自 MSDN :

用于不安全的代码上下文中,以在 堆栈.

Used in an unsafe code context to allocate a block of memory on the stack.

C#的主要功能之一是您通常不需要直接访问内存,就像在C/C ++中使用mallocnew那样.但是,如果您确实确实想显式分配一些内存,则可以,但是C#认为这是不安全的",因此,只有在使用unsafe设置进行编译时,您才可以这样做. stackalloc允许您分配此类内存.

One of the main features of C# is that you do not normally need to access memory directly, as you would do in C/C++ using malloc or new. However, if you really want to explicitly allocate some memory you can, but C# considers this "unsafe", so you can only do it if you compile with the unsafe setting. stackalloc allows you to allocate such memory.

几乎可以肯定,您不需要使用它来编写托管代码.在某些情况下,如果直接访问内存,则可以编写更快的代码是可行的-基本上,它允许您使用适合某些问题的指针操作.除非您有特定的问题并且不安全的代码是唯一的解决方案,否则您将可能永远不需要它.

You almost certainly don't need to use it for writing managed code. It is feasible that in some cases you could write faster code if you access memory directly - it basically allows you to use pointer manipulation which suits some problems. Unless you have a specific problem and unsafe code is the only solution then you will probably never need this.

这篇关于什么时候需要在C#中使用stackalloc关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆