使用子句中的C#Foreach值?

dee*_*392 1 c# visual-web-developer-2010

我正在尝试使用foreach控件循环遍历字符串数组,然后使用每个值在数据库中插入信息.有人可以帮我理解为什么在using子句中我不能使用foreach变量?

string[] ship_ids = ShipsInScope.Split('|');
foreach (string ship_id in ship_ids)
{
     using (SqlCommand InsertCommand = new SqlCommand("insert into PROJECT_SHIP (CR_Number, Ship_Id) VALUES (@CR_Number, @CCF_Number)", DBConn))
    {
         InsertCommand.Parameters.Add("@CR_Number", SqlDbType.NVarChar, 10).Value = CRNumber;
         InsertCommand.Parameters.Add("@Ship_Id", SqlDbType.NVarChar, 10).Value = Ship_Id;

         InsertCommand.ExecuteNonQuery();
         InsertCommand.Dispose();
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

C#区分大小写.您的迭代变量是,ship_id但您尝试Ship_Id在循环中使用.

理想情况下,使用C#命名约定(以及其他变量):

// Declared outside the method.
private const string InsertSql = 
    "insert into PROJECT_SHIP (CR_Number, Ship_Id) " +
    "VALUES (@CR_Number, @CCF_Number)";

...

string[] shipIds = ShipsInScope.Split('|');
foreach (string shipId in shipIds)
{
    using (SqlCommand command = new SqlCommand(InsertSql, connection))
    {
        command.Parameters.Add("@CR_Number", SqlDbType.NVarChar, 10)
                          .Value = crNumber; // Unclear what this means
        command.Parameters.Add("@Ship_Id", SqlDbType.NVarChar, 10)
                          .Value = shipId;
        command.ExecuteNonQuery();
    }
}
Run Code Online (Sandbox Code Playgroud)

笔记:

  • 将常量SQL提取为类级常量.没有必要,但可能会澄清事情.
  • 将所有变量重命名为camelCase没有下划线
  • StackOverflow的换行- 您可能不需要在代码中包含太多包装
  • 删除了冗余显式调用Dispose(因为using语句已调用Dispose)