班级成员会占用记忆吗? [英] Does class members occupy memory?

查看:51
本文介绍了班级成员会占用记忆吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个类通常由成员变量&方法.当我们创建一个类的实例时,会为一个类的成员变量分配内存.成员方法也占用内存吗?这些方法存储在哪里?

A class is composed normally of member variables & methods. When we create instance of a class, memory is allocated for member variables of a class. Does member methods also occupy memory? Where are these methods stored?

推荐答案

假设我们有以下课程:

public class Person
{
   public string Name { get; set; }

   public Person(string name)
   {
        Name = name;
   }

   public string SayName()
   {
      string hello = "Hello! My name is ";
      return hello + name;
   }
}

Person p = new Person("John");
string yourName = p.SayName();

SayName()函数在 Call Stack Person p 对象及其属性( Name )将保留在内存中,直到垃圾收集进入并清理为止.

The SayName() function goes on the Call Stack, and the Person p object and it's properties (Name) will stay in memory until the Garbage Collection comes in and cleans it up.

在内存方面,您应该更加关注对象的实例字段(属性),要处理的对象数量以及对象是否为 Reader 连接.如果您的对象是 Reader Connection ,则需要考虑使用 using 语句.

In terms of memory, you should be more concerned with the instance fields (properties) of the object, the amount of objects you are dealing with, and if your object is some time of Reader or Connection. If your object is a Reader or Connection you need to consider a using statement.

伪代码:

using(DatabaseConnection dbConn = new DatabaseConnection()
{
    // Process your calls and data
}
// The object is Disposable and it's resources are cleared 

这篇关于班级成员会占用记忆吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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