是否可以在堆栈上创建类的实例?
问题描述:
我知道在C ++中,您可以像在堆栈上那样创建类的实例
I know that in C++ you can create an instance of a class on the stack like
MyClass mc = MyClass(8.2);
或在堆上
MyClass * mc = new MyClass(8.2);
您可以在C#中做同样的事情吗?我曾经在C#中创建类的唯一方法是通过new
对其进行设置.
Can you do the same thing in C#? The only way I ever create a class in C# is by new
ing it.
答
否,这是不可能的.所有类的所有实例总是分配在堆上.
No, it's not possible. All instances of all classes are always allocated on the heap.
值类型(包括用户定义的struct
类型)可以保存值,而不是引用其他位置的值,它们可以将值存储在变量恰巧存储其值的任何位置,而可能不是堆
It is value types, including user defined struct
types, that hold values, rather than references to values elsewhere, that can store a value in whatever location that variable happens to store its value in, which may not be the heap.