gpt4 book ai didi

c# - c#中的using结构怎么样

转载 作者:行者123 更新时间:2023-11-30 13:07:52 25 4
gpt4 key购买 nike

我看到了这个:

using (StreamWriter sw = new StreamWriter("file.txt"))
{
// d0 w0rk s0n
}

我尝试查找的所有信息都没有解释这是做什么的,而是提供了有关 namespace 的信息。

最佳答案

您想查看 using statement 的文档(而不是关于命名空间的 using 指令)。

基本上这意味着该 block 被转换为 try/finally block ,并且 sw.Dispose() 在 finally 中被调用 block (通过适当的无效检查)。

无论何时处理实现 IDisposable 的类型,您都可以使用 using 语句 - 通常您应该将它用于您负责的任何一次性对象。

关于语法的一些有趣的部分:

  • 您可以在一条语句中获取多个资源:

    using (Stream input = File.OpenRead("input.txt"),
    output = File.OpenWrite("output.txt"))
    {
    // Stuff
    }
  • 您不必为变量赋值:

    // For some suitable type returning a lock token etc
    using (padlock.Acquire())
    {
    // Stuff
    }
  • 你可以在没有大括号的情况下嵌套它们;方便避免缩进

    using (TextReader reader = File.OpenText("input.txt"))
    using (TextWriter writer = File.CreateText("output.txt"))
    {
    // Stuff
    }

关于c# - c#中的using结构怎么样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2548240/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com