using System;
class ClassOfInts
{
public int x;
开发者_如何转开发public int y;
}
class Test
{
ClassOfInts objClassOfInts;
string name;
public TestMethod(int p, int q, string s)
{
objClassOfInts=new ClassofInts;
objClassOfInts.x=p;
objClassOfInts.y=q;
name=s;
}
}
class Main
{
static Main()
{
Test t1=new Test();
Test t2=new Test();
t1.TestMethod(1,2,"First");
//XXX
t2.TestMethod(2,3,"Second");
//YYY
}
}
What is the memory allocation of above program when it reaches XXX. Will reference variable objClassInts still be reffering to its object in Heap. or As soon as TestMethod finishes Execution, objClassInts will be reffering to null.
Each instance of Test
has its own objClassOfInts
instance. That instance will live as long as the Test
instance.
In your example, that means they will both live until the end of Main
.
BTW, it's a best practice to not use Hungarian notation. In "`objClassOfInts'" we assume it's an object of some kind. Objects aren't special in C# - they're expected.
I'm not sure I follow the question, but unless you set an object to null, if you still have access to it then the obect will still be there. The benefit of garbage collection is that objects do not surprisingly disappear in some parts of your code,they are only gotten rid of when you couldn't access them anyways.
When execution reaches XXXX, the object referenced by t1 is eligible for garbage collection. Which includes the object references held by its fields, objClassOfInts and name. When it reaches YYYY, both the objects referenced by t1 and t2 are eligible. In debug mode, they won't be eligible until the method exits. It says nothing about when they actually get collected, it can take a while.
objClassOfInts will not be null. It starts as null, but as long as a Test object is live, all it's referenced objects will also be live.
精彩评论