可以将对象进行上述using语句,而不是在括号内声明 [英] Can an object be declared above a using statement instead of in the brackets

查看:141
本文介绍了可以将对象进行上述using语句,而不是在括号内声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数在C#中使用语句的例子声明括号内的对象是这样的:

Most of the examples of the using statement in C# declare the object inside the brackets like this:

using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", connection))
{
   // Code goes here
}

如果我以下列方式使用using语句using语句外声明的对象会发生什么:

What happens if I use the using statement in the following way with the object declared outside the using statement:

SqlCommand cmd = new SqlCommand("SELECT * FROM Customers", connection);
using (cmd)
{
   // Code goes here
}

这是个坏主意,使用using语句我在第二个例子,为什么?

Is it a bad idea to use the using statement in the way I have in the second example and why?

推荐答案

声明using语句的控制表达式内部变量限制变量来using语句内的范围。在第二个例子中,变量 CMD 可以继续使用的语句(何时会被释放)后使用。

Declaring the variable inside the using statement's control expression limits the scope of the variable to inside the using statement. In your second example the variable cmd can continue to be used after the using statement (when it will have been disposed).

一般来说,建议只使用一个变量为一个目的,限制其范围更高版本允许的范围具有相同名称的另一个命令(也许在另一个使用表达式)。也许更重要的是它告诉读者你的代码(和维护需要更多的努力比最初写)的 CMD 未使用超出使用语句:你的代码是多一点点可以理解的。

Generally it is recommended to only use a variable for one purpose, limiting its scope allows another command with the same name later in scope (maybe in another using expression). Perhaps more importantly it tells a reader of your code (and maintenance takes more effort than initial writing) that cmd is not used beyond the using statement: your code is a little bit more understandable.

这篇关于可以将对象进行上述using语句,而不是在括号内声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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