“使用”有什么用? 在 C# 中?

发布于 2024-07-05 12:03:34 字数 245 浏览 11 评论 0 原文

用户 kokos 回答了精彩的C# 的隐藏功能 通过提及 using 关键字提出问题。 你能详细说明一下吗? 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(29

染柒℉ 2024-07-12 12:03:34

因为很多人仍然这样做:

using (System.IO.StreamReader r = new System.IO.StreamReader(""))
using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {
   //code
}

我想很多人仍然不知道你可以这样做:

using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {
   //code
}

Since a lot of people still do:

using (System.IO.StreamReader r = new System.IO.StreamReader(""))
using (System.IO.StreamReader r2 = new System.IO.StreamReader("")) {
   //code
}

I guess a lot of people still don't know that you can do:

using (System.IO.StreamReader r = new System.IO.StreamReader(""), r2 = new System.IO.StreamReader("")) {
   //code
}
不…忘初心 2024-07-12 12:03:34

像这样的事情:

using (var conn = new SqlConnection("connection string"))
{
   conn.Open();

    // Execute SQL statement here on the connection you created
}

这个SqlConnection将被关闭,而不需要显式调用.Close()函数,并且即使抛出异常也会发生这种情况 em>,不需要 try/catch/finally

Things like this:

using (var conn = new SqlConnection("connection string"))
{
   conn.Open();

    // Execute SQL statement here on the connection you created
}

This SqlConnection will be closed without needing to explicitly call the .Close() function, and this will happen even if an exception is thrown, without the need for a try/catch/finally.

说谎友 2024-07-12 12:03:34

using 子句用于定义特定变量的范围。

例如:

Using(SqlConnection conn = new SqlConnection(ConnectionString)
{
    Conn.Open()

    // Execute SQL statements here.
    // You do not have to close the connection explicitly
    // here as "USING" will close the connection once the
    // object Conn goes out of the defined scope.
}

The using clause is used to define the scope for the particular variable.

For example:

Using(SqlConnection conn = new SqlConnection(ConnectionString)
{
    Conn.Open()

    // Execute SQL statements here.
    // You do not have to close the connection explicitly
    // here as "USING" will close the connection once the
    // object Conn goes out of the defined scope.
}
唔猫 2024-07-12 12:03:34

使用 using 语句的原因是确保对象在超出范围后立即被释放,并且不需要显式代码来确保发生这种情况。

理解 C# 中的 'using' 语句(代码项目)使用实现 IDisposable (microsoft) 的对象,C# 编译器转换

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,引入了一种新语法,名为“使用声明":

using 声明是前面带有 using 关键字的变量声明。 它告诉编译器所声明的变量应该在封闭范围的末尾进行处理。

所以上面的等效代码是:

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

当控制离开包含范围(通常是一个方法,但也可以是一个代码块)时,myRes 将被释放。

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.

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();
}

to

{ // 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 introduces a new syntax, named "using declarations":

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();

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

若无相欠,怎会相见 2024-07-12 12:03:34

using 可用于调用 IDisposable。 它还可以用于别名类型。

using (SqlConnection cnn = new SqlConnection()) { /* Code */}
using f1 = System.Windows.Forms.Form;

using can be used to call IDisposable. It can also be used to alias types.

using (SqlConnection cnn = new SqlConnection()) { /* Code */}
using f1 = System.Windows.Forms.Form;
苍风燃霜 2024-07-12 12:03:34

使用,实际上

using (var foo = new Bar())
{
  Baz();
}

是 try/finally 块的简写。 它相当于代码:

var foo = new Bar();
try
{
  Baz();
}
finally
{
  foo.Dispose();
}

当然,您会注意到,第一个片段比第二个片段简洁得多,而且即使抛出异常,您也可能需要执行多种操作来进行清理。 因此,我们提出了一个名为 Scope 的类,它允许您在 Dispose 方法中执行任意代码。 因此,例如,如果您有一个名为 IsWorking 的属性,在尝试执行操作后您总是希望将其设置为 false,那么您可以这样做:

using (new Scope(() => IsWorking = false))
{
  IsWorking = true;
  MundaneYetDangerousWork();
}

您可以阅读有关我们的解决方案以及我们如何派生它的更多信息 此处

using, in the sense of

using (var foo = new Bar())
{
  Baz();
}

Is actually shorthand for a try/finally block. It is equivalent to the code:

var foo = new Bar();
try
{
  Baz();
}
finally
{
  foo.Dispose();
}

You'll note, of course, that the first snippet is much more concise than the second and also that there are many kinds of things that you might want to do as cleanup even if an exception is thrown. Because of this, we've come up with a class that we call Scope that allows you to execute arbitrary code in the Dispose method. So, for example, if you had a property called IsWorking that you always wanted to set to false after trying to perform an operation, you'd do it like this:

using (new Scope(() => IsWorking = false))
{
  IsWorking = true;
  MundaneYetDangerousWork();
}

You can read more about our solution and how we derived it here.

美胚控场 2024-07-12 12:03:34

Microsoft 文档指出 using 具有双重功能 (https: //msdn.microsoft.com/en-us/library/zhdeatwt.aspx),既作为指令,也作为语句。 作为一个声明,正如在其他答案中指出的那样,关键字基本上是语法糖,用于确定处置 IDisposable 对象的范围。 作为指令,它通常用于导入命名空间和类型。 另外,作为指令,您可以为命名空间和类型创建别名,如《C# 5.0 简而言之:权威指南》(http://www.amazon.com/5-0-Nutshell-The-Definitive-Reference-ebook/dp/B008E6I1K8) ,约瑟夫和本阿尔巴哈里。 一个例子:

namespace HelloWorld
{
    using AppFunc = Func<IDictionary<DateTime, string>, List<string>>;
    public class Startup
    {
        public static AppFunc OrderEvents() 
        {
            AppFunc appFunc = (IDictionary<DateTime, string> events) =>
            {
                if ((events != null) && (events.Count > 0))
                {
                    List<string> result = events.OrderBy(ev => ev.Key)
                        .Select(ev => ev.Value)
                        .ToList();
                    return result;
                }
                throw new ArgumentException("Event dictionary is null or empty.");
            };
            return appFunc;
        }
    }
}

这是一种明智的做法,因为滥用这种做法可能会损害代码的清晰度。 DotNetPearls (http://www.dotnetperls .com/using-alias)。

Microsoft documentation states that using has a double function (https://msdn.microsoft.com/en-us/library/zhdeatwt.aspx), both as a directive and in statements. As a statement, as it was pointed out here in other answers, the keyword is basically syntactic sugar to determine a scope to dispose an IDisposable object. As a directive, it is routinely used to import namespaces and types. Also as a directive, you can create aliases for namespaces and types, as pointed out in the book "C# 5.0 In a Nutshell: The Definitive Guide" (http://www.amazon.com/5-0-Nutshell-The-Definitive-Reference-ebook/dp/B008E6I1K8), by Joseph and Ben Albahari. One example:

namespace HelloWorld
{
    using AppFunc = Func<IDictionary<DateTime, string>, List<string>>;
    public class Startup
    {
        public static AppFunc OrderEvents() 
        {
            AppFunc appFunc = (IDictionary<DateTime, string> events) =>
            {
                if ((events != null) && (events.Count > 0))
                {
                    List<string> result = events.OrderBy(ev => ev.Key)
                        .Select(ev => ev.Value)
                        .ToList();
                    return result;
                }
                throw new ArgumentException("Event dictionary is null or empty.");
            };
            return appFunc;
        }
    }
}

This is something to adopt wisely, since the abuse of this practice can hurt the clarity of one's code. There is a nice explanation on C# aliases, also mentioning pros and cons, in DotNetPearls (http://www.dotnetperls.com/using-alias).

鲸落 2024-07-12 12:03:34

有趣的是,您还可以将 using/IDisposable 模式用于其他有趣的事情(例如 Rhino Mocks 使用它的方式的另一点)。 基本上,您可以利用编译器始终对“已使用”对象调用 .Dispose 的事实。 如果您需要在某个操作之后发生某些事情……有明确的开始和结束的事情……那么您可以简单地创建一个 IDisposable 类,该类在构造函数中开始操作,然后在 Dispose 方法中完成。

这允许您使用非常好的 using 语法来表示所述操作的显式开始和结束。 这也是 System.Transactions 的工作原理。

Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.

This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.

隱形的亼 2024-07-12 12:03:34

using 的另一个重要用途是实例化模式对话框。

Using frm as new Form1

    Form1.ShowDialog

    ' Do stuff here

End Using

Another great use of using is when instantiating a modal dialog.

Using frm as new Form1

    Form1.ShowDialog

    ' Do stuff here

End Using
紫轩蝶泪 2024-07-12 12:03:34

您可以通过以下示例来使用别名命名空间:

using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;

这称为 using alias 指令,如您所见,如果您想隐藏冗长的引用,它可以用于隐藏冗长的引用在你的代码中很明显你所指的是什么
例如

LegacyEntities.Account

代替

CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account

或简单地

Account   // It is not obvious this is a legacy entity

You can make use of the alias namespace by way of the following example:

using LegacyEntities = CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects;

This is called a using alias directive as as you can see, it can be used to hide long-winded references should you want to make it obvious in your code what you are referring to
e.g.

LegacyEntities.Account

instead of

CompanyFoo.CoreLib.x86.VBComponents.CompanyObjects.Account

or simply

Account   // It is not obvious this is a legacy entity
嘴硬脾气大 2024-07-12 12:03:34

只是添加了一些令我惊讶的东西并没有出现。 using 最有趣的特性(在我看来)是,无论你如何退出 using 块,它总是会释放该对象。 这包括退货和例外。

using (var db = new DbContext())
{
    if(db.State == State.Closed)
        throw new Exception("Database connection is closed.");
    return db.Something.ToList();
}

抛出异常或返回列表并不重要。 DbContext 对象将始终被释放。

Just adding a little something that I was surprised did not come up. The most interesting feature of using (in my opinion) is that no matter how you exit the using block, it will always dispose the object. This includes returns and exceptions.

using (var db = new DbContext())
{
    if(db.State == State.Closed)
        throw new Exception("Database connection is closed.");
    return db.Something.ToList();
}

It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.

追风人 2024-07-12 12:03:34

我过去经常使用它来处理输入和输出流。 您可以很好地嵌套它们,并且它可以消除您通常遇到的许多潜在问题(通过自动调用 dispose)。 例如:

        using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
        {
            using (BufferedStream bs = new BufferedStream(fs))
            {
                using (System.IO.StreamReader sr = new StreamReader(bs))
                {
                    string output = sr.ReadToEnd();
                }
            }
        }

I've used it a lot in the past to work with input and output streams. You can nest them nicely and it takes away a lot of the potential problems you usually run into (by automatically calling dispose). For example:

        using (FileStream fs = new FileStream("c:\file.txt", FileMode.Open))
        {
            using (BufferedStream bs = new BufferedStream(fs))
            {
                using (System.IO.StreamReader sr = new StreamReader(bs))
                {
                    string output = sr.ReadToEnd();
                }
            }
        }
长伴 2024-07-12 12:03:34

使用 ADO.NET 时,您可以将 keywork 用于连接对象或读取器对象等。 这样,当代码块完成时,它将自动释放您的连接。

When using ADO.NET you can use the keywork for things like your connection object or reader object. That way when the code block completes it will automatically dispose of your connection.

第七度阳光i 2024-07-12 12:03:34

“using”也可以用来解决命名空间冲突。

请参阅http://www.davidarno.org/c -howtos/aliases-overcoming-name-conflicts/ 我就该主题编写了一个简短的教程。

"using" can also be used to resolve namespace conflicts.

See http://www.davidarno.org/c-howtos/aliases-overcoming-name-conflicts/ for a short tutorial I wrote on the subject.

别闹i 2024-07-12 12:03:34

C# 中 using 关键字有两种用法,如下所示。

  1. 作为指令

    通常我们使用 using 关键字在代码隐藏和类文件中添加命名空间。 然后它使当前页面中的所有类、接口和抽象类及其方法和属性都可用。

    示例:

    使用 System.IO; 
      
  2. 作为声明

    这是在 C# 中使用 using 关键字的另一种方式。 它对于提高垃圾收集性能起着至关重要的作用。

    using 语句可确保即使在创建对象以及调用方法、属性等时发生异常,也会调用 Dispose()。 Dispose() 是 IDisposable 接口中提供的一种方法,有助于实现自定义垃圾收集。 换句话说,如果我正在执行一些数据库操作(插入、更新、删除),但不知何故发生异常,那么这里的 using 语句会自动关闭连接。 无需显式调用连接 Close() 方法。

    另一个重要因素是它有助于连接池。 .NET 中的连接池有助于消除多次关闭数据库连接的情况。 它将连接对象发送到池以供将来使用(下一次数据库调用)。 下次从应用程序调用数据库连接时,连接池将获取池中可用的对象。 因此它有助于提高应用程序的性能。 因此,当我们使用using语句时,控制器会自动将对象发送到连接池,无需显式调用Close()和Dispose()方法。

    您可以通过使用 try-catch 块执行与 using 语句相同的操作,并显式调用 finally 块内的 Dispose()。 但 using 语句会自动进行调用,使代码更干净、更优雅。 在 using 块内,对象是只读的,不能修改或重新分配。

    示例:

    string connString = "数据源=localhost;集成安全性=SSPI;初始目录=Northwind;"; 
    
      使用 (SqlConnection conn = new SqlConnection(connString)) 
      { 
            SqlCommand cmd = conn.CreateCommand(); 
            cmd.CommandText = "从客户中选择客户 ID、公司名称"; 
            conn.Open(); 
            使用 (SqlDataReader dr = cmd.ExecuteReader()) 
            { 
               while (dr.Read()) 
               Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1)); 
            } 
      } 
      

在前面的代码中,我没有关闭任何连接; 它会自动关闭。 由于 using 语句 (using (SqlConnection conn = new SqlConnection(connString)) 和对于 SqlDataReader 对象也是如此,如果发生任何异常,它将自动关闭连接。

有关详细信息,请参阅C# 中使用的用法和重要性

There are two usages of the using keyword in C# as follows.

  1. As a directive

    Generally we use the using keyword to add namespaces in code-behind and class files. Then it makes available all the classes, interfaces and abstract classes and their methods and properties in the current page.

    Example:

    using System.IO;
    
  2. As a statement

    This is another way to use the using keyword in C#. It plays a vital role in improving performance in garbage collection.

    The using statement ensures that Dispose() is called even if an exception occurs when you are creating objects and calling methods, properties and so on. Dispose() is a method that is present in the IDisposable interface that helps to implement custom garbage collection. In other words if I am doing some database operation (Insert, Update, Delete) but somehow an exception occurs then here the using statement closes the connection automatically. No need to call the connection Close() method explicitly.

    Another important factor is that it helps in Connection Pooling. Connection Pooling in .NET helps to eliminate the closing of a database connection multiple times. It sends the connection object to a pool for future use (next database call). The next time a database connection is called from your application the connection pool fetches the objects available in the pool. So it helps to improve the performance of the application. So when we use the using statement the controller sends the object to the connection pool automatically, there is no need to call the Close() and Dispose() methods explicitly.

    You can do the same as what the using statement is doing by using try-catch block and call the Dispose() inside the finally block explicitly. But the using statement does the calls automatically to make the code cleaner and more elegant. Within the using block, the object is read-only and cannot be modified or reassigned.

    Example:

    string connString = "Data Source=localhost;Integrated Security=SSPI;Initial Catalog=Northwind;";
    
    using (SqlConnection conn = new SqlConnection(connString))
    {
          SqlCommand cmd = conn.CreateCommand();
          cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";
          conn.Open();
          using (SqlDataReader dr = cmd.ExecuteReader())
          {
             while (dr.Read())
             Console.WriteLine("{0}\t{1}", dr.GetString(0), dr.GetString(1));
          }
    }
    

In the preceding code I am not closing any connection; it will close automatically. The using statement will call conn.Close() automatically due to the using statement (using (SqlConnection conn = new SqlConnection(connString)) and the same for a SqlDataReader object. And also if any exception occurs it will close the connection automatically.

For more information, see Usage and Importance of Using in C#.

我做我的改变 2024-07-12 12:03:34
public class ClassA:IDisposable
{
    #region IDisposable Members
    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
    #endregion
}

public void fn_Data()
{
    using (ClassA ObjectName = new ClassA())
    {
        // Use objectName
    }
}
public class ClassA:IDisposable
{
    #region IDisposable Members
    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }
    #endregion
}

public void fn_Data()
{
    using (ClassA ObjectName = new ClassA())
    {
        // Use objectName
    }
}
三生路 2024-07-12 12:03:34

当您使用实现 IDisposable 的类型的局部变量时,始终,无一例外地使用 using1

如果您使用非本地 IDisposable 变量,则始终实现 IDisposable 模式

两条简单的规则,可能有一个例外1。 否则防止资源泄漏是一个真正的痛苦。


1):唯一的例外是 – 当您处理异常时。 这样,在 finally 块中显式调用 Dispose 的代码可能会更少。

When you use a local variable of a type that implements IDisposable, always, without exception, use using1.

If you use nonlocal IDisposable variables, then always implement the IDisposable pattern.

Two simple rules, with possibly one exception1. Preventing resource leaks otherwise is a real pain.


1): The only exception is – when you're handling exceptions. It might then be less code to call Dispose explicitly in the finally block.

残龙傲雪 2024-07-12 12:03:34

using 用于当您想要在使用某个资源后将其释放时。

例如,如果您分配了一个文件资源,并且只需要在一段代码中使用它来进行少量读取或写入,则使用有助于在完成后立即处理文件资源。

正在使用的资源需要实现 IDisposable 才能正常工作。

例子:

using (File file = new File (parameters))
{
    // Code to do stuff with the file
}

using is used when you have a resource that you want disposed after it's been used.

For instance if you allocate a File resource and only need to use it in one section of code for a little reading or writing, using is helpful for disposing of the File resource as soon as your done.

The resource being used needs to implement IDisposable to work properly.

Example:

using (File file = new File (parameters))
{
    // Code to do stuff with the file
}
别忘他 2024-07-12 12:03:34

立即处置该对象的合理使用的另一个例子:

using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString)) 
{
    while (myReader.Read()) 
    {
        MyObject theObject = new MyObject();
        theObject.PublicProperty = myReader.GetString(0);
        myCollection.Add(theObject);
    }
}

Another example of a reasonable use in which the object is immediately disposed:

using (IDataReader myReader = DataFunctions.ExecuteReader(CommandType.Text, sql.ToString(), dp.Parameters, myConnectionString)) 
{
    while (myReader.Read()) 
    {
        MyObject theObject = new MyObject();
        theObject.PublicProperty = myReader.GetString(0);
        myCollection.Add(theObject);
    }
}
↘人皮目录ツ 2024-07-12 12:03:34

它还可用于创建示例范围:

class LoggerScope:IDisposable {
   static ThreadLocal<LoggerScope> threadScope = 
        new ThreadLocal<LoggerScope>();
   private LoggerScope previous;

   public static LoggerScope Current=> threadScope.Value;

   public bool WithTime{get;}

   public LoggerScope(bool withTime){
       previous = threadScope.Value;
       threadScope.Value = this;
       WithTime=withTime;
   }

   public void Dispose(){
       threadScope.Value = previous;
   }
}


class Program {
   public static void Main(params string[] args){
       new Program().Run();
   }

   public void Run(){
      log("something happend!");
      using(new LoggerScope(false)){
          log("the quick brown fox jumps over the lazy dog!");
          using(new LoggerScope(true)){
              log("nested scope!");
          }
      }
   }

   void log(string message){
      if(LoggerScope.Current!=null){
          Console.WriteLine(message);
          if(LoggerScope.Current.WithTime){
             Console.WriteLine(DateTime.Now);
          }
      }
   }

}

It also can be used for creating scopes for Example:

class LoggerScope:IDisposable {
   static ThreadLocal<LoggerScope> threadScope = 
        new ThreadLocal<LoggerScope>();
   private LoggerScope previous;

   public static LoggerScope Current=> threadScope.Value;

   public bool WithTime{get;}

   public LoggerScope(bool withTime){
       previous = threadScope.Value;
       threadScope.Value = this;
       WithTime=withTime;
   }

   public void Dispose(){
       threadScope.Value = previous;
   }
}


class Program {
   public static void Main(params string[] args){
       new Program().Run();
   }

   public void Run(){
      log("something happend!");
      using(new LoggerScope(false)){
          log("the quick brown fox jumps over the lazy dog!");
          using(new LoggerScope(true)){
              log("nested scope!");
          }
      }
   }

   void log(string message){
      if(LoggerScope.Current!=null){
          Console.WriteLine(message);
          if(LoggerScope.Current.WithTime){
             Console.WriteLine(DateTime.Now);
          }
      }
   }

}
救赎№ 2024-07-12 12:03:34

对我来说,“using”这个名字有点令人困惑,因为它可以是导入命名空间或语句(如此处讨论的)以进行错误处理的指令。

错误处理的不同名称会很好,而且也许是一个更明显的名称。

For me the name "using" is a little bit confusing, because is can be a directive to import a Namespace or a statement (like the one discussed here) for error handling.

A different name for error handling would've been nice, and maybe a somehow more obvious one.

一杆小烟枪 2024-07-12 12:03:34

大括号之外的所有内容都已被丢弃,因此如果您不使用对象,最好将其丢弃。 之所以如此,是因为如果您有一个 SqlDataAdapter 对象,并且在应用程序生命周期中仅使用它一次,并且您只填充一个数据集并且不再需要它,则可以使用以下代码:

using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))
{
   // do stuff
} // here adapter_object is disposed automatically

Everything outside the curly brackets is disposed, so it is great to dispose your objects if you are not using them. This is so because if you have a SqlDataAdapter object and you are using it only once in the application life cycle and you are filling just one dataset and you don't need it anymore, you can use the code:

using(SqlDataAdapter adapter_object = new SqlDataAdapter(sql_command_parameter))
{
   // do stuff
} // here adapter_object is disposed automatically
鼻尖触碰 2024-07-12 12:03:34

当您使用 using 时,它将在 using 作用域末尾调用对象上的 Dispose() 方法。 因此,您可以在 Dispose() 方法中包含大量出色的清理代码。

要点:

如果您实现 IDisposable,请确保在 Dispose() 实现中调用 GC.SuppressFinalize(),否则自动垃圾收集将尝试在某个时刻出现并最终确定它,这至少会造成浪费资源(如果您已经 Dispose()d 了)。

When you use using, it will call the Dispose() method on the object at the end of the using's scope. So you can have quite a bit of great cleanup code in your Dispose() method.

A bullet point:

If you implement IDisposable, make sure you call GC.SuppressFinalize() in your Dispose() implementation, as otherwise automatic garbage collection will try to come along and Finalize it at some point, which at the least would be a waste of resources if you've already Dispose()d of it.

爱情眠于流年 2024-07-12 12:03:34

并不是说它非常重要,但是使用也可以用于动态更改资源。

是的,如前所述,是一次性的,但也许您不希望在其余执行过程中资源与其他资源不匹配。 所以你想处理掉它,这样它就不会干扰其他地方。

Not that it is ultra important, but using can also be used to change resources on the fly.

Yes, disposable as mentioned earlier, but perhaps specifically you don't want the resources they mismatch with other resources during the rest of your execution. So you want to dispose of it so it doesn't interfere elsewhere.

清君侧 2024-07-12 12:03:34

using 关键字定义对象的范围,然后在范围完成时释放该对象。 例如。

using (Font font2 = new Font("Arial", 10.0f))
{
    // Use font2
}

有关 C# 的 MSDN 文章,请参阅此处 使用关键字。

The using keyword defines the scope for the object and then disposes of the object when the scope is complete. For example.

using (Font font2 = new Font("Arial", 10.0f))
{
    // Use font2
}

See here for the MSDN article on the C# using keyword.

夜深人未静 2024-07-12 12:03:34

Rhino Mocks 记录播放语法using 进行了有趣的使用。

The Rhino Mocks Record-playback Syntax makes an interesting use of using.

平生欢 2024-07-12 12:03:34

using 语句告诉 .NET 在不再需要时释放 using 块中指定的对象。

因此,您应该对需要在之后进行清理的类使用“using”块,例如 System.IO 类型。

The using statement tells .NET to release the object specified in the using block once it is no longer needed.

So you should use the 'using' block for classes that require cleaning up after them, like System.IO types.

数理化全能战士 2024-07-12 12:03:34

using 作为语句自动调用指定的 dispose
目的。 该对象必须实现 IDisposable 接口。 这是
可以在一个语句中使用多个对象,只要它们是
相同类型。

CLR 将您的代码转换为 CILusing 语句被转换为 try 和finally 块。 这就是 using 语句在 CIL 中的表示方式。 using 语句被翻译成三个部分:获取、使用和处置。 首先获取资源,然后将使用情况包含在带有 finally 子句的 try 语句中。 然后该对象在finally子句中被释放。

using as a statement automatically calls the dispose on the specified
object. The object must implement the IDisposable interface. It is
possible to use several objects in one statement as long as they are
of the same type.

The CLR converts your code into CIL. And the using statement gets translated into a try and finally block. This is how the using statement is represented in CIL. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause.

╭⌒浅淡时光〆 2024-07-12 12:03:34

using 语句提供了一种正确使用 IDisposable 对象的便捷机制。 通常,当您使用 IDisposable 对象时,应在 using 语句中声明并实例化它。

using 语句以正确的方式调用对象上的 Dispose 方法,并且(当您如前面所示使用它时)它还会导致对象本身在调用 Dispose 后立即超出范围。 在 using 块中,对象是只读的,不能修改或重新分配。

这来自此处

The using statement provides a convenience mechanism to correctly use IDisposable objects. As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement.

The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

This comes from here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文