问题
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?
回答1:
Say we have the following class:
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();
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.
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.
Pseudo-code:
using(DatabaseConnection dbConn = new DatabaseConnection()
{
// Process your calls and data
}
// The object is Disposable and it's resources are cleared
回答2:
Class s just a blue print, It doesn't occupy any space as long as variable of type class has not defined. Once the object/instance of type class is define, the class member will occupy some space in memory. And the size of instance is equal to the sum of the size of members define in class.
来源:https://stackoverflow.com/questions/11166956/does-class-members-occupy-memory