在引用类型中声明的值类型在哪里存储在C#的内存中

在引用类型中声明的值类型在哪里存储在C#的内存中

本文介绍了在引用类型中声明的值类型在哪里存储在C#的内存中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1>值类型存储在堆栈中。

2>对象存储在堆上。

3>因此引用类型中的值类型也存储在堆中。

4>但我们不能单独声明值类型,即我们必须将它们包装在一个类中并创建对象来访问它们。

5>以这种方式,第一个陈述是矛盾的。



请帮助我,因为我在不同的文章中得到不同的东西,所以不能得出结论。



我尝试了什么:



我已经查看了不同的文章但不满意,因为我变得与众不同并且反应矛盾。

1> value types are stored in the stack .
2> objects are stored on the heap.
3> So the value types inside the reference types are also stored in heap.
4> But we cant declare value types independently i.e we have to wrap them up in a class and create objects to access them.
5> in this way the 1st statement is contradicted.

Please help me as i am getting different things in different articles, so cant conclude.

What I have tried:

I have looked into different articles but not satisfied as i am getting different and contradicting responses.

推荐答案

引用:

值类型存储在堆栈中。







static int x; // is this on the stack? :)





对象存储在堆中,该对象中的所有属性(甚至是值类型)都是该对象的一部分,因此它们是也在堆上。



Objects are stored in the heap and all properties in that object (even value types) are a part of that object so they are also on the heap.


class Foo
{
    int x = 42;
    string s = "Bar";
}



和该类型的实例:


and an instance of that type:

Foo f = new Foo();



f 存储数据的地址对于该实例 - 例如: 0x1234567 。该数据可能类似于:


f stores the address of the data for that instance - eg: 0x1234567. That data might look something like:

// i:
0x1234567:   0
0x1234568:   0
0x1234569:   0
0x1234570:  42

// Address of s:
0x1234571:  11
0x1234572: 173
0x1234573: 240
0x1234574:  13



i 的数据以内联方式存储: 42 。但 s 的数据存储在其他地方,地址 0x0BADF00D


The data for i is stored inline: 42. But the data for s is stored somewhere else, at address 0x0BADF00D:

0x0BADF009:   0 // Length
0x0BADF00A:   0
0x0BADF00B:   0
0x0BADF00C:   3
0x0BADF00D:  66 // "B"
0x0BADF00E:  97 // "a"
0x0BADF00F: 114 // "r"



当然,这会忽略 [],其存储方式与参考类型相同。



更多轻读::)

[]

[]

[]


Of course, this ignores the concept of "boxed" value types[^], which are stored in the same way as reference types.

Some more light reading: :)
The Truth About Value Types – Fabulous Adventures In Coding[^]
Debunking another myth about value types – Fabulous Adventures In Coding[^]
Six important .NET concepts: Stack, heap, value types, reference types, boxing, and unboxing[^]


这篇关于在引用类型中声明的值类型在哪里存储在C#的内存中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 01:25