using 语句是否保留对其接收的对象的引用?

Does using statement keep a reference to object(s) it receive?

当使用这样的 "using" 语句时:

  using (Global.Instance.BusyLifeTrackerStack.GetNewLifeTracker())
  {
    ...

而不是

  using (var lt = Global.Instance.BusyLifeTrackerStack.GetNewLifeTracker())
  {
    ...

"using" 语句是否会保留对返回对象的引用,以确保它不会太早被垃圾回收?...如果没有为其声明显式变量(第一个示例代码)?

第二个示例代码显然没问题,但是第一个???

任何文档 and/or 参考信息将不胜感激。

是的,保留了一个真正的引用,以便最后调用Dispose方法。当您不明确需要访问 using 块内的一次性对象时,此模式通常用于在处置中执行某种“副作用”。比如在Razor中using(Html.BeginForm){...}允许对返回对象的处理在末尾输出</form>标签。

C# 中的一个简单示例是:

public class MessageGenerator : IDisposable
{
    public MessageGenerator()
    {
        Console.WriteLine("To whom it may concern,");
    }
    
    public void Dispose()
    {
        Console.WriteLine("Thanks and goodbye.");
    }
}

像这样的用法:

using (new MessageGenerator())
{
    Console.WriteLine("Please give me lots of reputation.");
}

会给出这样的输出:

To whom it may concern,

Please give me lots of reputation

Thanks and goodbye.

回答问题的文档和参考部分:

documentation for the using statement 注释:

The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

就第一个代码块的语法而言,C# standard 的语法如下:

using_statement
    : 'using' '(' resource_acquisition ')' embedded_statement
    ;

resource_acquisition
    : local_variable_declaration
    | expression
    ;

在那里,您会注意到 resource_acquisition 可以是局部变量声明或表达式,这是您的第一个代码块使用的内容。

这里是 an example 编译器在幕后所做的事情。代码如下:

using (File.OpenRead("Test.txt")){}

...转换为:

FileStream fileStream = File.OpenRead("Test.txt");
try
{
}
finally
{
    if (fileStream != null)
    {
        ((IDisposable)fileStream).Dispose();
    }
}

声明了一个变量,其中包含对所用对象的引用。