c#中“using”关键字的使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1769358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 20:39:46  来源:igfitidea点击:

use of "using" keyword in c#

c#.netasp.net

提问by Naruto

i want to know what is the use of "using" keyword in c#, i am new to it.. when we need to use "using" keyword.. i googled it, could not be satisfied with answers. still i want to know some more from you Geeks..

我想知道在 C# 中“using”关键字的用途是什么,我是新手。我仍然想从你那里了解更多 Geeks..

Thanks

谢谢

采纳答案by Jon Skeet

Two uses:

两种用途:

  • Using directives, e.g.

    using System;
    using System.IO;
    using WinForms = global::System.Windows.Forms;
    using WinButton = WinForms::Button;
    

    These are used to import namespaces (or create aliases for namespaces or types). These go at the top of the file, before any declarations.

  • Using statementse.g.

    using (Stream input = File.OpenRead(filename))
    {
        ...
    }
    

    This can only be used with types that implement IDisposable, and is syntactic sugar for a try/finally block which calls Disposein the finally block. This is used to simplify resource management.

  • 使用指令,例如

    using System;
    using System.IO;
    using WinForms = global::System.Windows.Forms;
    using WinButton = WinForms::Button;
    

    这些用于导入命名空间(或为命名空间或类型创建别名)。这些位于文件的顶部,在任何声明之前。

  • 使用语句例如

    using (Stream input = File.OpenRead(filename))
    {
        ...
    }
    

    这只能与实现的类型一起使用IDisposable,并且是调用 finally 块的 try/finally 块的语法糖Dispose。这用于简化资源管理。

回答by Elisha

usinghas two meanings in C#:

using在 C# 中有两个含义:

  • usingfor IDisposablemeans that when the block of using ends Disposemethod will be called.
  • usingfor namespacemeans that the types from the imported namespace will be referenced in code.
  • usingfor IDisposable意味着当 using 块结束时Dispose将调用方法。
  • usingfor namespace意味着来自导入的命名空间的类型将在代码中被引用。

Basic example of how using block works:

使用块如何工作的基本示例:

A "dummy" disposable class:

一个“虚拟”的一次性类:

public class DisposableClass : IDisposable
{
    public static bool WasDisposed { get; private set;}

    public void Dispose()
    {
        WasDisposed = true;
    }
}

Some very simple code that demonstrates when Dispose is called:

一些非常简单的代码演示了何时调用 Dispose:

[Test]
public void DisposeSample()
{
    using (var disposableClass = new DisposableClass())
    {
        Assert.IsFalse(DisposableClass.WasDisposed);
    }

    Assert.IsTrue(DisposableClass.WasDisposed);
}

回答by James

Pretty sure there will be a duplicate of this one somewhere....however, in short the using keywords is used to specify the scope of the object you are creating. The object is disposed once it exits the using block i.e. Dispose is called automatically.

很确定在某处会有这个副本的副本......但是,简而言之, using 关键字用于指定您正在创建的对象的范围。该对象一旦退出 using 块即被处理,即自动调用 Dispose。

See using Statement (C#)for more details.

有关更多详细信息,请参阅using Statement (C#)

回答by jaywon

It gives you an easy way to cleanup resources after you are done with them. With the usingconstruct, once you are done usingthe resources, they are freed automatically. It even cleans up the resources in the case of an exception.

它为您提供了一种在完成资源后清理资源的简单方法。使用using构造,一旦您使用完资源,它们就会自动释放。它甚至会在发生异常时清理资源。

回答by Greg Beech

There are three uses:

有以下三种用途:

I don't believe I can explain more clearly than the MSDN articles in general terms. If you have trouble understanding them, you might be better to post a more specific question regarding the details you don't understand.

我不相信我可以用一般术语比 MSDN 文章更清楚地解释。如果您在理解它们时遇到困难,最好针对您不理解的细节发布更具体的问题。

回答by Razzie

There are two uses of the 'using' keyword:

“using”关键字有两种用法:

  • as a using directive, which permits the use of types in a namespace. For example: using System.Web
  • as a using statement, which is only possible for types that inherit from IDisposable. This automatically calls the Dispose()method on the object after the using statement goes out of scope, so you don't have to worry about automatically calling this method yourself, or calling Close()on database connections, for example:

    using(MySqlConnection connection = new MySqlConnection()) { //.. }

  • 作为 using指令,它允许在命名空间中使用类型。例如:using System.Web
  • 作为 using语句,这仅适用于继承自 的类型IDisposable。这会Dispose()在 using 语句超出范围后自动调用对象上的方法,因此您不必担心自己自动调用此方法,或调用Close()数据库连接,例如:

    using(MySqlConnection connection = new MySqlConnection()) { //.. }

回答by Vadym Stetsiak

"using" keyword can also be used to make type aliases. Here Item is an alias to Dictionary. This approach can save you some typing :)

“using”关键字也可用于创建类型别名。这里的 Item 是 Dictionary 的别名。这种方法可以为您节省一些打字时间:)

For instance,

例如,

using Item = System.Collections.Generic.Dictionary<string, string>;
namespace Sample
{
    using Records = Dictionary<int, Item>;
    public class Controller
    {
      Records recordDictionary = new Records();
    }
}

回答by Adrian Zanescu

I assume you'r talking about the using control block and not the using [namespace] statement. Basically the keyword is syntactic sugar for safely initializing and disposing objects. It works with any object that implements IDisposable. The following:

我假设您在谈论 using 控制块而不是 using [namespace] 语句。基本上,关键字是用于安全初始化和处置对象的语法糖。它适用于任何实现 IDisposable 的对象。下列:

using(MyType obj = new MyType())
{
  ... do stuff.
}

is equivalent to:

相当于:

MyType obj = new MyType();
try
{
  .... do stuff
}
finally
{
  if(obj != null)
  {
      obj.Dispose();
  }
}