在代码中间解释 C# 代码中的 using 语句...(不在 header 中作为加载库)

Explain using statement in C# code in middle of code... (not in header as loading libraries)

拜托,任何人都可以用 c# "using" 向我解释一下语句。我知道我在程序 header 处使用它来加载基本库,例如使用 System.Text;。但我不清楚,有什么区别:

using (var font1 = new Font("Arial", 10.0f)) 
{
    byte charset = font1.GdiCharSet;
}

和:

using var font1 = new Font("Arial", 10.0f);
byte charset = font1.GdiCharSet;

是的,我阅读了 C# 的手册,但我并不真正理解这一点。

using 与实现 IDisposable 接口的类型结合使用。

它确保当对象超出范围时,调用 Dispose 方法(如 IDisposable 中定义)并且通常用于处理非托管资源。

您的第一个示例是传统的 using 块,其中对象范围由以下 {} 定义。

您的第二个是 C#8 中引入的新 using 语句,其中作用域是封闭块,与其他局部变量一样。

大致相当于:

var font1 = new Font("Arial", 10.0f);
byte charset = font1.GdiCharSet;
font1.Dispose();

但正如 Casey 所指出的,它实际上确保了对象被处置,即使在块内抛出异常,即

var font1 = new Font("Arial", 10.0f);
try
{
    byte charset = font1.GdiCharSet;
}
finally
{
    if (font1 != null)
    {
        font1.Dispose();
    }
}

using 在 c# 中有多种含义。

它可用于将名称空间导入 class,如您在 System.Text 示例中所述。这是一个using directive

当您在代码中使用非托管资源(如 SQLConnection、流等)时,它们通常会实现 IDisposable 接口。当您使用实现此接口的类型时,您必须在使用完此类型后调用 dispose 方法。

为了简化此模式的使用,尤其是在发生异常时,C# 引入了 using 语句 - 它会自动为您调用 dispose。

在 C#8 中,引入了不需要任何花括号的简化语法。

您可以了解有关使用 here and here 的更多信息。