是否可以在堆栈上创建类的实例? [英] Is it possible to create an instance of a class on the stack?

查看:59
本文介绍了是否可以在堆栈上创建类的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道在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 newing 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.

这篇关于是否可以在堆栈上创建类的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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