类的内存管理
在以下代码中,就内存管理而言,如何在 .NET (C#) 中分配和释放A 类
。
class A
{
public static m1(int x, int y)
{
int x, y;
return x+y;
}
int m2(int p, int q)
{
int p, int q;
return p+q;
}
int x=10;
int y;
const int x=10;
readOnly y=20;
public int x
{
get {y}
set {y=value}
}
}
class B
{
A a=new A(); // what happens when initializing class A;
}
注意:B 类
的使用可以是程序的入口点,也可以是对象实例,但这里的范围是A 类
实例的内存管理和分配。 /代码>。
in the following code, How - in terms of memory management - is class A
allocated and deallocated in .NET (C#).
class A
{
public static m1(int x, int y)
{
int x, y;
return x+y;
}
int m2(int p, int q)
{
int p, int q;
return p+q;
}
int x=10;
int y;
const int x=10;
readOnly y=20;
public int x
{
get {y}
set {y=value}
}
}
class B
{
A a=new A(); // what happens when initializing class A;
}
Note: that the usage of class B
could be either the entry point of the program, or an object instance, but the scope here is on memory management and allocation of the instance of class A
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您创建
B
的新实例时,您描述的行会在堆上分配A
的单个实例。因此,将分配两个对象:一个用于直接调用的
B
和一个作为构造B
的一部分的A
。在您创建
B
实例之前,该行本身不执行任何操作。A 似乎有三个不是引用字段的字段,因此它不会在堆上创建新对象,而是 A 实例的一部分。
这大致就是本示例中分配的所有内存。
编辑:
为了更清楚起见 - 解释堆栈和堆以及内存分配注意事项的文章的参考链接:
http://www.simple-talk。 com/dotnet/.net-framework/.net-内存管理-basics/
The line you describes allocates a single instance of
A
on the heap when you create a new instance ofB
. So,will allocate two objects: one
B
with the direct call and oneA
as part of constructing theB
.The line itself does nothing until you create an instance of
B
.A
seems to have three fields which are not reference fields, so it does not create new objects on the heap but are part of theA
instance.That's roughly all the memory that's allocated in this example.
EDIT:
For purposes of greater clarity - A reference link to an article explaining Stack and Heap, and Memory Allocation considerations:
http://www.simple-talk.com/dotnet/.net-framework/.net-memory-management-basics/
当您创建 B 的实例时,内存将分配给具有一个引用类型(“A”)字段的 1 个对象。在创建 A 的新实例之后,这会导致为具有两个“int”字段(“x”、“y”)和一个 TYPE IS UNKNOWN 类型字段的对象分配内存。
When you create an instance of B, the memory is allocated for 1 object with one field of reference type ("A"). Right after that new instance of A is created which causes allocation of memory for object with two "int" fields ("x", "y") and with one field of TYPE IS UNKNOWN type.