在c#中访问for循环外的变量

本文关键字:变量 循环 for 访问 | 更新日期: 2023-09-27 18:09:09

这里我需要在for循环之外访问变量delval,如下面的代码

cmd_mail.Parameters.Add("@deleteusers", SqlDbType.NVarChar).Value = delval;

. .如何做到这一点……

我的代码

 for (int i = 0; i <= NoOfUsers - 1; i++) {
        using (SqlConnection Conn = new SqlConnection(constr_str)) {
            using (SqlCommand cmd = new SqlCommand()) {
                cmd.Connection = Conn;
                Conn.Open();
                cmd.CommandText = "Select top 1 Login_User_Name  from Rode_Provisioning_User where RequestId=@RequestId and CustomerCode =@CustomerCode and disableflag=0 order by User_Count";
                cmd.Parameters.Add("@CustomerCode", SqlDbType.VarChar).Value = CustomerCode;
                cmd.Parameters.Add("@RequestId", SqlDbType.VarChar).Value = RequestId;
                string Loginusername = cmd.ExecuteScalar();
                Conn.Close();
                string delval = "";
                if (string.IsNullOrEmpty(delval)) {
                    delval = Loginusername;
                } else {
                    delval = delval + "," + Loginusername;
                }
            }
        }
        }
    if (flag == "Yes") {
        string constr_dep = "server=" + _strServer + ";database=" + _strDatabase + ";uid=" + _strUserid + ";pwd=" + _strPassword + ";";
        SqlConnection con_dep = new SqlConnection();
        con_dep.ConnectionString = constr_dep;
        SqlCommand cmd_mail = new SqlCommand("delete_user_mailsend_sp", con_dep);
        cmd_mail.CommandType = CommandType.StoredProcedure;
        cmd_mail.CommandTimeout = 0;
        cmd_mail.Parameters.Add("@companycode", SqlDbType.NVarChar).Value = CustomerCode
        cmd_mail.Parameters.Add("@deleteusers", SqlDbType.NVarChar).Value = delval;
            try {
            con_dep.Open();
            cmd_mail.ExecuteNonQuery();
        } catch (SqlException ee) {
            VWLogger.LogMessage("Exception in delete_user_mailsend_sp:", TraceEventType.Critical);
            VWLogger.LogMessage(ee, TraceEventType.Critical);
            return ee.Message;
            flag = ee.Errors(0).ToString();
        }
        con_dep.Close();
    }

任何建议吗?

在c#中访问for循环外的变量

然后在循环外定义它,它将在两个块中以及外部可见。

正如zerkms所说,在循环外声明它。见下文.

string delval = "";
for (int i = 0; i <= NoOfUsers - 1; i++) 
{
    // your existing stuff
    // ...
    if (string.IsNullOrEmpty(delval)) 
    {
        delval = Loginusername;
    }
    else
    {                     
        delval = delval + "," + Loginusername;                 
    }
}
if (flag == "Yes") 
{           
    // your existing stuff
    // ...
    cmd_mail.Parameters.Add("@deleteusers", SqlDbType.NVarChar).Value = delval;
}