stackalloc
关键字提供了什么功能?何时和为什么我会想要使用它?stackalloc
关键字提供了什么功能?何时和为什么我会想要使用它?从 MSDN:
在不安全代码的上下文中使用,以在堆栈上分配一块内存。
C# 的主要特点之一是您通常不需要直接访问内存,就像您在 C/C++ 中使用 malloc
或 new
一样。但是,如果您真的想显式分配一些内存,您可以这样做,但 C# 认为这是“不安全的”,因此只有在编译时使用 unsafe
设置才能这样做。 stackalloc
允许您分配此类内存。
您几乎肯定不需要为编写托管代码而使用它。在某些情况下,您可能会通过直接访问内存来编写更快的代码-基本上它允许您使用指针操作,这适用于某些问题。除非您有一个具体的问题并且不安全的代码是唯一的解决方案,否则您 可能 永远不需要使用它。
使用stackalloc可以在堆栈上分配数据,这可以用于避免在方法内重复创建和销毁值类型数组所产生的垃圾。
public unsafe void DoSomeStuff()
{
byte* unmanaged = stackalloc byte[100];
byte[] managed = new byte[100];
//Do stuff with the arrays
//When this method exits, the unmanaged array gets immediately destroyed.
//The managed array no longer has any handles to it, so it will get
//cleaned up the next time the garbage collector runs.
//In the mean-time, it is still consuming memory and adding to the list of crap
//the garbage collector needs to keep track of. If you're doing XNA dev on the
//Xbox 360, this can be especially bad.
}
managed
变量,有时也可能被分配到栈上。 - user1804599http://msdn.microsoft.com/en-us/library/cx9s2sy4.aspx
this关键字用于处理不安全的内存操作。使用它,您可以使用指针(C / C ++中强大而痛苦的功能)
就像 Steve 指出的那样,它只在不安全代码上下文中使用(例如,当您想要使用指针时)。
如果您的 C# 应用程序中不使用不安全代码,则永远不需要使用它。