何时将值类型存储在stack(C#)中? [英] When are value types stored in stack(C#)?

查看:51
本文介绍了何时将值类型存储在stack(C#)中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我阅读下一本书值和引用类型"时,我想到一个问题:什么时候将值类型存储在堆栈中"?导致程序员无法初始化类外的任何值类型.原因是当我们在类中初始化一些值类型的变量时,变量被存储在堆中.

When I read next book of chapter "Value and reference types" then a question comes to my mind: "When are value types stored in stack"? Cause programmer cannot initialise any value type out of class. Cause when we initialise some variable of value type in class then variable is stored in heap.

我的问题是:何时将值类型存储在堆栈中?

My question is: when are value types stored in stack?

推荐答案

首先,您很少需要知道,但是基本上,值类型存储在它们所拥有的任何位置 .

Well, firstly it is very rare that you would need to know, but basically, value-types are stored where-ever they are owned.

当它们是线程执行流的一部分时,它们被存储在堆栈中 ,这可能意味着:

They are stored on the stack when they are part of the execution flow of a thread, which can mean:

  • 在本地"(方法变量)中-排除某些情况(如下)
  • 作为方法的一部分中的浮点值,即,一个方法的返回值即将作为值传递给另一个方法-不涉及本地",但该值仍在堆栈中
      按值传递的
    • 值类型参数(即没有 ref out )只是这种情况的特殊情况
    • in a "local" (a method variable) - excluding some cases (below)
    • as a floating value in part of a method, i.e. the return value from one method that is about to be passed as a value to another method - no "local" is involved, but the value is still on the stack
      • value-type parameters that are passed by-value (i.e. without ref or out) are simply a special-case of this

      在以下情况下,它们被存储在堆中(作为对象的一部分):

      They are stored on the heap (as part of an object) when:

      • 在类的实例字段"中
      • 在本身在堆上的值类型的实例字段"中
      • 在静态字段"中
      • 在数组中
      • 位于局部"(方法变量)中,该局部变量是迭代器块,异步方法的一部分,或者是lambda或匿名方法中的捕获"变量(所有这些都会导致将局部提升到编译器生成的类上的字段)
      • 装箱"时-即转换为引用类型( object dynamic Enum ValueType (是: ValueType 是引用类型;很有趣,是吗?), ISomeInterface 等)
      • in an instance "field" on a class
      • in an instance "field" on a value-type that is itself on the heap
      • in a static "field"
      • in an array
      • in a "local" (a method variable) that is part of an iterator block, an async method, or which is a "captured" variable in a lambda or anonymous method (all of which cause the local to be hoisted onto a field on a class that is generated by the compiler)
      • when "boxed" - i.e. cast into a reference-type (object, dynamic, Enum, ValueType (yes: ValueType is a reference-type; fun, eh?), ISomeInterface, etc)

      这篇关于何时将值类型存储在stack(C#)中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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