我有以下类,有以下方法:
public class Foo
{
public string A {get;set;}
public static Foo New(string a)
{
Foo newFoo = new Foo();
newFoo.A = a;
return newFoo;
}
}
public class Bar
{
public void SomeMethod()
{
...
Foo anotherFoo = Foo.New("a");
....
}
}
Run Code Online (Sandbox Code Playgroud)
如果Bar类在使用上面的代码的过程中创建Foo,那么Foo是否会超出范围并获得垃圾收集,或者Foo(因为它使用的是静态方法)继续引用变量newFoo,因此anotherFoo永远不会去超出范围?
静态方法的存在不会影响对象对GC的合格性,只会引用该对象的引用.在你的情况下anotherFoo将是唯一的参考.newFoo当方法返回时,引用超出范围,弹出堆栈.
静态方法中的局部变量本身并不是"静态的",当方法返回时,那些局部变量将从执行堆栈中弹出,与非静态方法相同.
返回anotherFoo时后面的底层对象将符合GC的条件SomeMethod(好吧,编译器更具攻击性,并且当anotherFoo代码中不再使用GC时它可以使GC成为可能).