码迷,mamicode.com
首页 > Windows程序 > 详细

C# 8.0的新的using语法——Using declarations

时间:2019-01-26 00:22:59      阅读:870      评论:0      收藏:0      [点我收藏+]

标签:不用   htm   eth   scope   lin   stat   dispose   options   模式   

我们在代码中经常使用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

 看起来舒服多了有没有。

 

C# 8.0的新的using语法——Using declarations

标签:不用   htm   eth   scope   lin   stat   dispose   options   模式   

原文地址:https://www.cnblogs.com/TianFang/p/10322359.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!