“使用”的用途是什么?在C#中? [英] What are the uses of "using" in C#?

查看:108
本文介绍了“使用”的用途是什么?在C#中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

用户 kokos 回答了美妙的 C#的隐藏功能 问题,其中提到了 using 关键字。您能详细说明一下吗? 使用有什么用?

User kokos answered the wonderful Hidden Features of C# question by mentioning the using keyword. Can you elaborate on that? What are the uses of using?

推荐答案

using 语句用于确保对象在超出范围后立即被处置,并且不需要显式代码来确保这种情况发生。

The reason for the using statement is to ensure that the object is disposed as soon as it goes out of scope, and it doesn't require explicit code to ensure that this happens.

了解C#(代码项目) 使用实现IDisposable(Microsoft)的对象 ,C#编译器将转换

As in Understanding the 'using' statement in C# (codeproject) and Using objects that implement IDisposable (microsoft), the C# compiler converts

using (MyResource myRes = new MyResource())
{
    myRes.DoSomething();
}

{ // Limits scope of myRes
    MyResource myRes= new MyResource();
    try
    {
        myRes.DoSomething();
    }
    finally
    {
        // Check for a null resource.
        if (myRes != null)
            // Call the object's Dispose method.
            ((IDisposable)myRes).Dispose();
    }
}

C#8引入了一种新语法,名为 使用声明

C# 8 introduces a new syntax, named "using declarations":


using声明是一个变量声明,其后是using关键字。它告诉编译器声明的变量应该放在封闭范围的末尾。

A using declaration is a variable declaration preceded by the using keyword. It tells the compiler that the variable being declared should be disposed at the end of the enclosing scope.

因此,上面的等效代码将是:

So the equivalent code of above would be:

using var myRes = new MyResource();
myRes.DoSomething();

当控件离开包含作用域时(通常是一种方法,但也可以是代码块) ,将处置 myRes

And when control leaves the containing scope (usually a method, but it can also be a code block), myRes will be disposed.

这篇关于“使用”的用途是什么?在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆