假设我已经定义了以下方法。
static object F()
{
return new object();
}
如果我编写如下代码,则object在范围结束之前不能对返回的内容进行垃圾收集。
{
object x = F();
// cannot yet garbage collect the object
// returned by F (referenced as variable x)
}
// can now garbage collect the object
// returned by F (referenced as variable x)
如果我编写如下代码,返回object后可以立即进行垃圾回收F。
{
F();
// can now garbage collect the object
// returned by F
}
但是现在假设我将定义更改为F以下内容。
static IDisposable F()
{
return new SomeDisposableObject();
}
如果我编写如下代码,返回的对象不能被垃圾收集,直到using块结束才会被释放。
using (IDisposable x = F())
{
} // immediately x.Dispose()
// can now garbage collect the object
// returned by F
如果我编写如下代码,行为是什么?对 C# 语言规范的引用是一个加号。
using (F())
{
}
块是否using算作对返回的实例的引用F?