是一个int类里面存储的堆栈还是堆? [英] Is an int inside a class stored on the stack or the heap?

查看:586
本文介绍了是一个int类里面存储的堆栈还是堆?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

堆栈&堆理解问题

我在我使用var实际上是慢?如果是这样,为什么?值类型存储在堆栈中,类类型存储在堆中。

I was told in Is using var actually slow? If so, why? that value types are stored on the stack and class types are stored in the heap.

class MyClass
{
  private int myInt;
  private int[] myInts;
}

MyClass.myInt 存储? MyClass 是一个类/引用类型,所以它在堆上。 myInt 是一个值类型,因此它存储在某种内部堆栈?

Where is MyClass.myInt stored? MyClass is a class/reference type, so it's on the heap. myInt is a value type, so is it stored on some kind of "inside stack"?

关于数组?是值还是类?

Also, what about the array? Is it a value or a class?

推荐答案


放入堆

value types are put into stack and class types get put into heap

只有一半是真的,特别是下半部分。参考类型存储在堆中,这总是为真。

Only half of that is true, specifically the second half. Reference types are stored in the heap, that is always true.

第一部分不是真的,或者只是真实的。作为局部变量的值类型存储在堆栈中,但作为类或结构体成员的值类型存储在该类型中。框中的值类型存储在堆上的对象内。

The first part is not true, or rather only true sometimes. Value types that are local variables are stored on the stack, but value types that are member of a class or struct are stored inside that type. Value types that are boxed are stored inside an object on the heap.

因此, MyClass 包含整数和引用,类的实例将始终存储在堆上。

So, an instance of your MyClass will contain an integer and a reference, and the instance of the class will always be stored on the heap.

数组是一个单独的对象,也将始终存储在堆。如果实际上有一个数组,那就是。在创建数组并赋值给 myInts 之前,它是 null ,并且没有数组。

The array is a separate object, and will also always be stored on the heap. If there actually is an array, that is. Until you have created an array and and assigned to myInts, it's null and there is no array.

这篇关于是一个int类里面存储的堆栈还是堆?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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