当一个对象被方法返回时,它会一直存在,直到不再有对它的引用。此时,它会受到垃圾收集。因此,一个对象不会因为创建它的方法终止而被销毁。
2 回答
这意味着在下面的场景中,在您调用 之后,即使它是私有对象Run()
,也不会被垃圾收集。a
那是因为_b
存在于方法的范围之外,并且仍然持有对a
.
class Test
{
private B _b;
public void Run()
{
A a = new A();
_b = new B(a);
}
}
public class A
{
}
public class B
{
private A _a;
public B(A a)
{
_a = a;
}
}
If you have:
string Method1()
{
return new Random().Next(0, 1000).ToString();
}
Then when you call it, it creates a Random
object, and soon afterwards a string
object.
Once the method is done using the Random
object by calling Next
(note, whether the method has returned or not has absolutely nothing to do with this, regardless of what that book might say). there's no more references to it anywhere that any code will reach it by, so it might be collected.
If though the string was obtained in:
void Method2()
{
string s = Method1();
//s isn't collected here by devious forces.
Console.WriteLine(s);//this works.
}
So the book is saying "things don't magically disappear when you use them.
It's actually incorrect, in:
void Method3()
{
Method1();
}
There's no reason to suspect that the string wasn't collected before the method method returned.
But also:
static string blah
void Method4()
{
blah = new Random().Next(0, 10).ToString();
}
This didn't return anything, but it created an object that won't be collected.
Also:
void Method5(out string ret)
{
ret = new Random().Next(0, 10).ToString();
}
void Method 6()
{
string s;
Method5(out s);
//s isn't collected here by devious forces.
Console.WriteLine(s);//this works.
}
Here's a better version:
"Once there is no way that any code which will run could use the object, it may be collected."
Buy a better book, there's no point asking people to explain what Herbert Schildt says about something, because that assumes he's correct. Frankly, I'd be more worried about the bits you thought you understood than the bits you were confused by, because you won't know if it was actually correct or bullschildt.