C# 为什么不能在静态方法中使用using语句?
如果我在类中这样使用,当我从默认值调用它时,它会正常工作。cs:C# 为什么不能在静态方法中使用using语句?,c#,sql,asp.net,ado.net,C#,Sql,Asp.net,Ado.net,如果我在类中这样使用,当我从默认值调用它时,它会正常工作。cs: public class MyMethodsSql { public static SqlDataReader MetodoCommand() { string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString; SqlConnection con = new SqlCon
public class MyMethodsSql
{
public static SqlDataReader MetodoCommand()
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from Employees";
con.Open();
cmd.Connection = con;
SqlDataReader sdr = cmd.ExecuteReader();
return sdr;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
GridView1.DataSource = MyMethodsSql.MetodoCommand();
GridView1.DataBind();
}
但是当我使用using语句时,我得到一个错误:表示没有打开的连接
public class MyMethodsSql
{
public static SqlDataReader MetodoCommand()
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from Employees";
con.Open();
cmd.Connection = con;
SqlDataReader sdr = cmd.ExecuteReader();
return sdr;
}
}
}
SQLConnection将在返回datareader之前关闭/释放自身,datareader需要一个打开的连接。当您退出关闭括号时,using语句将关闭连接。当连接关闭时,SqlDataReader也关闭了。好,这意味着我应该在结尾使用con.Close()而不是use语句;在一个try-catch和finally中,但决不能使用?@AlexMartinez:关闭连接与处理连接具有相同的效果。如果要返回数据读取器,则无法关闭方法中的连接。为了使职责合理,您应该将连接发送到方法并返回读取器,或者在方法中进行读取,以便关闭连接并返回数据。您仍然可以使用using语句,将con作为类的私有变量,并在MyMethodsSql上实现IDisposable,在构造函数中打开sql连接,并在Dispose()中关闭连接,这样调用方就可以在SqlConnection和MyMethodsSql感谢您的评论!