软件编程
位置:首页>> 软件编程>> C#编程>> C#8.0新语法using declaration

C#8.0新语法using declaration

作者:天方  发布时间:2023-10-23 00:57:54 

标签:C#,using,declaration

我们在代码中经常使用using保障非托管资源的释放 

static void Main(string[] args)
{
   using (var options = Parse(args))
   {
       if (options["verbose"]) { WriteLine("Logging..."); }
       ...
   } // options disposed here
}

using虽然释放数据非常有效,但是有的时候会带来过多的缩进,导致代码不好阅读。 

using (var a = ...)
{
   //do something 1
   using (var a = ...)
   {
       //do something 2
       using (var a = ...)
       {
           //do something 3
       }
   }
}

在C# 8.0中引入了一个新的using语法,可以不用花括号,变量出了其生命周期自动释放。  该语 * 能上有点类似于C++的scoped_ptr,不过也支持async模式下的自动dispose。

static void Main(string[] args)
{
   using var options = Parse(args);
   if (options["verbose"]) { WriteLine("Logging..."); }
} // options disposed here

在新语法的加持下,上面的代码就可以简化如下

using var a = ...;
//do something 1

using var b = ...;
//do something 2

using var c = ...;
//do something 3

看起来舒服多了有没有。

来源:https://www.cnblogs.com/TianFang/p/10322359.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com