【问题标题】:'using' keyword before local variable declaration in C#? [duplicate]在 C# 中的局部变量声明之前使用'using'关键字? [复制]
【发布时间】:2020-07-10 11:30:55
【问题描述】:

您好,我在浏览 C# 中的一些示例时遇到了一些类似于以下的代码:

private void WriteData(string filePath)
{
    using var writer = new System.IO.StreamWriter(filePath);

    //Logic to write data here
}

想知道using在变量声明中的用途和意义。 还有它与简单的变量声明有什么不同:

var writer = new System.IO.StreamWriter(filePath);

【问题讨论】:

标签: c# .net using


【解决方案1】:

它是传统 using 语句的 C# 8 语法糖,可确保为实现 IDisposable 接口的类型调用 Dispose() 方法。

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement#example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 2017-05-16
    相关资源
    最近更新 更多