“使用”的目的是什么?使用时按以下方式食用

发布于 2024-09-05 15:49:04 字数 1566 浏览 8 评论 0原文

当以下列方式使用时,“使用”的目的是什么:-

这是一个例子,(一个答案 - @richj - 使用此代码来解决问题,谢谢)

private Method(SqlConnection connection)
{
    using (SqlTransaction transaction = connection.BeginTransaction())
    {
        try
        {
            // Use the connection here
            ....

            transaction.Commit();
        } 
        catch
        {
            transaction.Rollback();
            throw;
        }
    }
}

我在微软支持网站上阅读时发现的其他例子

public static void ShowSqlException(string connectionString)
{
    string queryString = "EXECUTE NonExistantStoredProcedure";
    StringBuilder errorMessages = new StringBuilder();

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        try
        {
            command.Connection.Open();
            command.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            for (int i = 0; i < ex.Errors.Count; i++)
            {
                errorMessages.Append("Index #" + i + "\n" +
                    "Message: " + ex.Errors[i].Message + "\n" +
                    "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                    "Source: " + ex.Errors[i].Source + "\n" +
                    "Procedure: " + ex.Errors[i].Procedure + "\n");
            }
            Console.WriteLine(errorMessages.ToString());
        }
    }
}

我正在顶部做页面的使用 system.data.sqlclient 等所以为什么在代码中间使用这个东西,

如果我省略它会怎么样(我知道代码会工作)但是我会失去什么功能

What purpose does “using” serve when used the following way:-

ONE EXAMPLE IS THIS, (AN ANSWERER- @richj - USED THIS CODE TO SOLVE A PROBLEM THANKS)

private Method(SqlConnection connection)
{
    using (SqlTransaction transaction = connection.BeginTransaction())
    {
        try
        {
            // Use the connection here
            ....

            transaction.Commit();
        } 
        catch
        {
            transaction.Rollback();
            throw;
        }
    }
}

OTHER EXAMPLE I FOUND WHILE READING ON MICROSOFT SUPPORT SITE

public static void ShowSqlException(string connectionString)
{
    string queryString = "EXECUTE NonExistantStoredProcedure";
    StringBuilder errorMessages = new StringBuilder();

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        try
        {
            command.Connection.Open();
            command.ExecuteNonQuery();
        }
        catch (SqlException ex)
        {
            for (int i = 0; i < ex.Errors.Count; i++)
            {
                errorMessages.Append("Index #" + i + "\n" +
                    "Message: " + ex.Errors[i].Message + "\n" +
                    "LineNumber: " + ex.Errors[i].LineNumber + "\n" +
                    "Source: " + ex.Errors[i].Source + "\n" +
                    "Procedure: " + ex.Errors[i].Procedure + "\n");
            }
            Console.WriteLine(errorMessages.ToString());
        }
    }
}

I AM doing at top of page as using system.data.sqlclient etc so why this using thing in middle of code,

What if I omit it (I know the code will work) but what functionality will I be losing

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

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

发布评论

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

评论(5

哭泣的笑容 2024-09-12 15:49:04

当您离开 using() 块时,您的连接将被关闭或执行类似的清理职责。这是通过调用对象的 Dispose() 方法来实现的。

When you leave the using() block your connection will be closed or similar cleanup duties are performed. This is achieved by calling the object's Dispose() method.

十雾 2024-09-12 15:49:04

我认为您指的是 using 关键字的两种不同用法。

当(通常)位于文件顶部时,它声明导入名称空间。请参阅“使用指令”

using System.Collections;

namespace XYZ
{
}

当在函数内部声明时,它会声明变量的有限生命周期和可能的范围(如果同时声明),以便在块关闭后自动调用它的 IDisposable 接口。请参阅“使用声明”

public void MyMethod()
{
    using (var conn = new SqlConnection(...))
    {
         // Do stuff
    }
}

相当于:

public void MyMethod()
{
    SqlConnection conn;
    try
    {
        conn = new SqlConnection(...);
        // Do stuff
    }
    finally
    {
        conn.Dispose();
    }
}

I think you are referring to two different usages of the using keyword.

When (generally) at the top of a file, it declares to import a namespace. See "using Directive".

using System.Collections;

namespace XYZ
{
}

When declared inside a function, it declares a limited lifetime and possibly scope (if declaring at the same time) for a variable such that it's IDisposable interface is automatically called after the block is closed. See "using Statement".

public void MyMethod()
{
    using (var conn = new SqlConnection(...))
    {
         // Do stuff
    }
}

Is the equivalient to:

public void MyMethod()
{
    SqlConnection conn;
    try
    {
        conn = new SqlConnection(...);
        // Do stuff
    }
    finally
    {
        conn.Dispose();
    }
}
帝王念 2024-09-12 15:49:04

直接来自 MSDN:

using (Font font1 = new Font("Arial", 10.0f)) 
{
  byte charset = font1.GdiCharSet;
}

相当于:

{
  Font font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}

它更短、更简洁换句话说:我想用我创建的这个东西来做各种美妙的事情,并且我希望框架在我用完它后清理我的游乐场。

它通常与分配资源(流、数据库连接...)的类一起使用,因为当您使用完这些资源时,您可能会忘记或忽略释放它们。
使用using,您无需与资源管理协调,并且很可能不会泄漏资源。

PS 另一个使用(如使用System.Web)是using 指令,我所说的是 using 语句

Straight from MSDN:

using (Font font1 = new Font("Arial", 10.0f)) 
{
  byte charset = font1.GdiCharSet;
}

is equivalent with:

{
  Font font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}

It's a shorter and more concise way of saying: I want to use this thing I creates for all kinds of wonderful things, and I want the framework to clean up my playground when I'm done with it.

It's usually used with classes that allocate resources (Streams, Database connections...) because you might forget or neglect to free those resources when you are done with them.
With using you don't concert yourself with resource management, and it's very likely that you won't leak resources.

P.S. The other using (as in using System.Web) is the using directive, the thing I'm talking about is the using statement.

忆梦 2024-09-12 15:49:04

在幕后,它将代码包装在 try/finally 块中,并在 finally 块中调用 IDiposable.Dispose() 确保清除所有资源。

基本上,它可以让您免去执行以下操作的麻烦:

SqlTransaction transaction = connection.BeginTransaction();

try
{ 
  //some code;
}
finally
{
  transaction.Dispose();
}

Behind the scenes, it wraps your code in a try/finally block, and in the finally block calls IDiposable.Dispose() ensuring any resources are cleaned up.

Basically it saves you the headache of doing:

SqlTransaction transaction = connection.BeginTransaction();

try
{ 
  //some code;
}
finally
{
  transaction.Dispose();
}
栩栩如生 2024-09-12 15:49:04

正如 Thief Master 所说 - 当退出 using 块时,SQLTransaction 或 SQLConnection 将关闭。无论它是通过返回还是抛出异常退出。

如果您省略使用,则必须自行关闭事务/连接。通过使用系统会自动为您完成此操作。

As Thief Master said - when the using block is exited the SQLTransaction or SQLConnection is closed. No matter if it exits through a return or by throwing an exception.

If you omit the using you have to close the transaction / connection by yourself. By use using the system does this for you automatically.

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