加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将一个使用块包装在另一个使用块中 – 是否过度杀伤?

发布时间:2020-12-16 00:04:57 所属栏目:百科 来源:网络整理
导读:我在我的项目中有一段代码,我在另一个使用块中包含一个使用块,我想知道这是一个好习惯还是矫枉过正(请注意我明白这是一个非常简单的代码片段,它是仅用于说明目的): protected void Submit_Click(object sender,EventArgs e) { try { using (SqlConnection c
我在我的项目中有一段代码,我在另一个使用块中包含一个使用块,我想知道这是一个好习惯还是矫枉过正(请注意我明白这是一个非常简单的代码片段,它是仅用于说明目的):

protected void Submit_Click(object sender,EventArgs e)
    {
        try
        {
            using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
            {
                cn.Open();

                string cmdStr = "SELECT COUNT(*) FROM REGISTRATION WHERE UserName ='" + this.TextBoxUN.Text + "' ";
                using (SqlCommand selectUser = new SqlCommand(cmdStr,cn))
                {
                    int temp = Convert.ToInt32(selectUser.ExecuteScalar().ToString());

                    if (temp == 0)
                    {
                        string insCmd = "Insert INTO REGISTRATION (UserName,Password,EmailAddress,FullName,Country) VALUES (@UserName,@Password,@EmailAddress,@FullName,@Country)";
                        using (SqlCommand insertUser = new SqlCommand(insCmd,cn))
                        {
                            try
                            {
                                insertUser.Parameters.AddWithValue("@UserName",this.TextBoxUN.Text);
                                insertUser.Parameters.AddWithValue("@Password",this.TextBoxPass.Text);
                                insertUser.Parameters.AddWithValue("@EmailAddress",this.TextBoxEA.Text);
                                insertUser.Parameters.AddWithValue("@FullName",this.TextBoxFN.Text);
                                insertUser.Parameters.AddWithValue("@Country",this.DropDownListCountry.SelectedItem.ToString());

                                insertUser.ExecuteNonQuery();
                                Response.Redirect("~/Login.aspx");
                            }
                            catch (Exception ex)
                            {
                                Response.Write(ex.Message);
                            }
                        }
                    }
                    else
                    {
                        Response.Write("User already Exists in Database");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
    }
}

解决方法

是.好的做法.在尽可能小的范围内处理物品,否则你将它留在GC做一段时间以后.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读