如果我们有一个类abc {int a,int b},我们创建类的对象。变量a,b和类存储的对象在哪里 [英] if we have a class abc{ int a, int b} and we create object of class. where does variable a ,b and object of class store
问题描述
如果我们有一个班级abc
公共班级abc
{
int a;
int b;
}
如果我们创建类的对象
abc obj = new abc();
这个对象和变量会保存在哪里?在堆或堆栈上?
在c#中的堆上创建类。
读取:http://stackoverflow.com/questions/15520378/memory-allocation-of-class-objects [ ^ ]
< blockquote>对象本身的 abc
的实例进入堆。至于对该对象的引用,它取决于 obj
是什么。如果这是变量,则它在堆栈中。但是,例如,如果它是某个类的实例成员,它也会使用该类的实例进入堆。如果这是静态成员,它会转到静态内存区域。
如果这里有不清楚的地方,你需要明白,如果你有一些成员或变量在引用类型中,您正在处理两个不同的对象:对象本身(始终在堆上)和指向此对象的引用(托管指针)。这很重要,因为您可以对同一个对象有两个不同的引用,一个引用,零引用等等。
在这种情况下,obj
存储在堆中。
public class abc
{
int a;
int b;
}
abc obj = new abc();
您可以考虑obj
作为数据的句柄或指针(如果你知道C ++)。obj
指向的数据存储在堆中。将obj
视为整数数据。请考虑以下代码:
abc a = new abc();
abc b = a;
现在,a
和b
是相同数据的句柄。在这里,这个分配不是那么昂贵,从逻辑上讲,它只是复制一个整数值。与C ++不同,在托管语言中,您无法获取对象的地址,因为垃圾收集器将移动对象。但是你可以使用GetHashCode
函数。所以,
Console.WriteLine(a.GetHashCode()+ 等于 + b.GetHashCode());
if we have a class abc
public class abc
{
int a;
int b;
}
if we create object of class
abc obj=new abc();
where does this object and variables will save? on heap or stack?
Classes are created on the heap in c#.
Read this : http://stackoverflow.com/questions/15520378/memory-allocation-of-class-objects[^]
The instance ofabc
, the object itself, goes to the heap. As to the reference to this object, it depends on whatobj
is. If this is the variable, it is on stack. But if, for example, it is an instance member of some class, it also goes to the heap with the instance of the class. If this is a static member, it goes to the area of static memory.
If something is unclear here, you need to understand that if you have some member or variable of reference type, you are dealing with two different objects: the object itself (always on heap) and the reference (managed pointer) pointing to this object. This is important, because you can have two different references to the same object, one reference, zero references, and so on.
—SA
In this case,obj
is stored in the heap.
public class abc { int a; int b; } abc obj = new abc();
You may considerobj
as a handle or a pointer(if you know C++) to the data. The data pointed to byobj
is stored in the heap. Treatobj
as an integral data. Consider the following code,
abc a = new abc(); abc b = a;
Now, botha
andb
are handles to the same data. Here this assignment is not so costly, logically, it just copies an integral value. Unlike C++, in managed languages you can't get the address of the object, as the garbage collector shall move the object. But you can use theGetHashCode
function. So,
Console.WriteLine(a.GetHashCode() + " is equal to " + b.GetHashCode());
这篇关于如果我们有一个类abc {int a,int b},我们创建类的对象。变量a,b和类存储的对象在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!